Python类声明中的变量用法 [英] Variable Usage in Python Class Declaration

查看:96
本文介绍了Python类声明中的变量用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Zed Shaw的学习Python的艰难方法教程40的代码片段:

Here is a code snippet from Zed Shaw's "Learn Python the Hard Way" tutorial 40:

class Song(object):

    def __init__(self, lyrics):
        self.lyrics = lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print line

为什么Python在定义时允许使用 self.lyrics sing_me_a_song功能?是因为在 init 下定义的变量
也可以在同一类的其他地方使用?

Why does Python allow "self.lyrics" to be used when defining "sing_me_a_song" function? Is it because whatever variable is defined under "init" can also be used elsewhere in the same class?

谢谢。

推荐答案

实例变量

此被称为实例变量。任何以 self。作为前缀定义的变量都可以在对象的任何方法中使用。通常,此类变量是在 __ init __ 中创建的,因此尽管您可以在其他方法中定义实例变量,但也可以从初始化对象开始对其进行访问。例如:

This is called an instance variable. Any variable defined with self. as a "prefix" can be used in any method of an object. Typically such variables are created in __init__, so they can be accessed from the moment the object is initialized, though you can define instance variables in other methods. For example:

>>> class foo:
...     def fun(self):
...             self.heh=3
... 
>>> f = foo()
>>> f.heh 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: foo instance has no attribute 'heh'
>>> f.fun()
>>> f.heh
3

请注意在<$ c $之外初始化实例变量的危险c> __ init __ ;如果在尝试访问它们之前未调用其初始化方法,则会出现错误。

Notice the danger in initializing instance variables outside of __init__; if the method in which they are initialized is not called before you try to access them, you get an error.

类变量

这不要与类变量混淆,类变量是可以由类的任何方法访问的另一种变量类型。可以为整个类设置类变量,而不仅仅是该类的特定对象。这是一个同时包含实例变量和类变量的示例类,以显示差异:

This is not to be confused with "class variables," which are another type of variable that can be accessed by any method of a class. Class variables can be set for an entire class, rather than just specific objects of that class. Here's an example class with both instance and class variables to show the difference:

class MyClass:
    classVar = "I'm a class var."
    def __init__(self):
        self.instanceVar = "I'm an instance var."
    def fun(self):
        methodVar = "I'm a method var; I cannot be accessed outside of this method."
        self.instanceVar2 = "I'm another instance var, set outside of __init__."

关于方法与功能的说明

在您的问题中,您称 sing_me_a_song 为函数。实际上,它是 Song 类的方法。这与常规的旧函数不同,因为它从根本上与类关联,因此也与该类的对象关联。

In your question, you call sing_me_a_song a "function." In reality, it is a method of the class Song. This is different from a regular old function, because it is fundamentally linked up with the class, and thus objects of that class as well.

这篇关于Python类声明中的变量用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆