Python 数据属性和方法属性的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28798781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Differences between data attributes and method attributes
提问by Leandros López
What is a method attribute, and a data attribute? What the difference between them and what they have in common?
什么是方法属性和数据属性?它们之间有什么区别,又有什么共同点?
I was reading python 2.7.9 (https://docs.python.org/2/tutorial/classes.html#random-remarks) and suddenly both became hard to understand. I'll appreciate some light over it.
我正在阅读 python 2.7.9 ( https://docs.python.org/2/tutorial/classes.html#random-remarks),突然两者都变得难以理解。我会很感激的。
采纳答案by Blckknght
An attribute is a variable that is looked up on another object using dot syntax: obj.attribute
. The way Python is designed, attribute lookups can do a variety of things, and that variety can sometimes lead to bugs if you don't really understand what is happening (this is what the documentation you linked to warns about).
属性是使用点语法在另一个对象上查找的变量:obj.attribute
. Python 的设计方式,属性查找可以做各种各样的事情,如果您不真正了解正在发生的事情(这是您链接到的文档警告的内容),这种多样性有时会导致错误。
The most basic issue is that an attribute lookup can find either a value stored in the object's instance dictionary, or it can find something from the object's class (or a base class, if there's inheritance going on). Methods are functions stored in the class, but you usually use them by looking them up on an instance (which "binds" the method, inserting the object as the first arguemnt when the method is called).
最基本的问题是属性查找可以找到存储在对象实例字典中的值,或者它可以从对象的类(或基类,如果有继承)中找到一些东西。方法是存储在类中的函数,但您通常通过在实例上查找它们来使用它们(“绑定”方法,在调用方法时将对象作为第一个参数插入)。
The exact sequence of what is checked when is a bit complicated (I described the full process in an answer to another question), but at the most basic level, instance attributes usually take precedence over class attribute.
检查内容的确切顺序有点复杂(我在另一个问题的回答中描述了完整过程),但在最基本的层面上,实例属性通常优先于类属性。
If an instance attribute and a class attribute with the same name both exist, usually only the instance attribute will be accessible. This can be very confusing if it is unintended.
如果同名的实例属性和类属性都存在,通常只有实例属性是可访问的。如果是无意的,这可能会非常令人困惑。
Consider the following code:
考虑以下代码:
class Foo(object):
def __init__(self, lst):
self.lst = lst
def sum(self):
self.sum = sum(self.lst)
return self.sum
f = Foo([1,2,3])
print(f.sum())
print(f.sum())
At the bottom of this code, we make two identical calls. The first works just fine, but the second will raise an exception.
在这段代码的底部,我们进行了两个相同的调用。第一个工作正常,但第二个会引发异常。
This is because the first time we look up f.sum
we find a method in the Foo
class. We can call the method with no problems. The trouble comes from the fact that the sum
method assigns the result of its calculation (the sum of the elements in self.lst
) to an instance attribute also named sum
. This hides the sum
method from view.
这是因为我们第一次查找时f.sum
会在Foo
类中找到一个方法。我们可以毫无问题地调用该方法。问题来自于该sum
方法将其计算结果( 中的元素的总和self.lst
)分配给同样名为 的实例属性的事实sum
。这将隐藏该sum
方法。
When second f.sum()
call looks up f.sum
, it finds the instance attribute, containing the integer 6
, rather than the expected method. An integer is not callable, so we get an exception.
当第二次f.sum()
调用查找时f.sum
,它会找到包含整数的实例属性6
,而不是预期的方法。一个整数是不可调用的,所以我们得到一个异常。
The solution, of course, is not to use the same name for the method and attribute. The code above is a pretty trivial example. The bugs caused by this sort of thing in more complex code can be much more difficult to figure out.
当然,解决方案不是对方法和属性使用相同的名称。上面的代码是一个非常简单的例子。在更复杂的代码中由此类事情引起的错误可能更难以弄清楚。
If you're writing code that adds attributes to objects you don't know much about, you should be careful to avoid common names. If you're writing a mixin class, consider using two leading underscores in the attribute names to trigger Python's name mangling, which is designed for exactly this sort of situation.
如果您正在编写向不太了解的对象添加属性的代码,则应小心避免使用通用名称。如果您正在编写一个 mixin 类,请考虑在属性名称中使用两个前导下划线来触发 Python 的名称修改,这正是为这种情况而设计的。
回答by Malik Brahimi
An attribute is any thing for the lack of a better word that is bound to an object, for example:
属性是指缺少绑定到对象的更好词的任何事物,例如:
class Dog:
def __init__(self):
self.name = "Rufus"
def bark(self):
print "Woof Woof!"
In this case the data attribute is the name, which is simply a value that is bound to the instance of the Dog. As for a method attribute, one answer would be the bark method, as it's not so much a value as it is an action. It's just as it is in English. A data attribute is exactly as it sounds; it's data, it is simply a property. A method is a procedure, an action, and this is exactly what a method attribute is.
在这种情况下,数据属性是名称,它只是一个绑定到 Dog 实例的值。至于方法属性,一个答案是 bark 方法,因为它与其说是一个值,不如说是一个动作。就像英语一样。数据属性正如其名;它是数据,它只是一个属性。方法是一个过程,一个动作,而这正是方法属性的含义。
回答by CrazyCasta
An attribute is basically anything that you can do instance.attribute_name
with. For instance in:
属性基本上是您可以instance.attribute_name
使用的任何东西。例如在:
class Hello(object):
def __init__(self, word):
self.word = word
def greet(self):
print "Hello: "+self.word
__init__
, greet
and word
would all be attributes. I would guess that a method is anything that is declared with def at the class scope (as opposed to doing self.func = lambda x:x*x for instance). In this case you get into bound vs unbound methods and the like. The important part being that for a member attribute when you do instance.method_name
you get back a bound method, which when you call it will call the original method with the instance as the first argument.
__init__
,greet
并且word
都是属性。我猜想一个方法是在类范围内用 def 声明的任何东西(而不是做 self.func = lambda x:x*x 例如)。在这种情况下,您将进入绑定与未绑定方法等。重要的部分是对于成员属性,当您instance.method_name
返回一个绑定方法时,当您调用它时,它将以实例作为第一个参数调用原始方法。
Also, after reading some of that section their wording is somewhat confusing/erroneous. For instance they say "Data attributes override method attributes with the same name", which as far as I know would be better put as instance attribute override class attributes with the same name. From the example I gave if we expanded this to:
此外,在阅读了该部分的一些内容后,他们的措辞有些令人困惑/错误。例如,他们说“数据属性覆盖具有相同名称的方法属性”,据我所知,最好将其作为实例属性覆盖具有相同名称的类属性。从我给出的示例中,如果我们将其扩展为:
class Hello(object):
greeting = "Hello: "
def __init__(self, word):
self.word = word
def greet(self):
print self.greeting+self.word
Then we could do:
然后我们可以这样做:
>>> a = Hello("world")
>>> a.greeting = "Goodbye "
>>> a.greet()
"Goodbye world"
This due to the fact that we put an instance attribute of greeting over the class attribute of greeting. Since methods defined in the class (the usual way) are class attributes they will be overridden by any instance attributes (data or otherwise).
这是因为我们将 greeting 的实例属性放在了 greeting 的 class 属性上。由于在类中定义的方法(通常的方式)是类属性,它们将被任何实例属性(数据或其他)覆盖。
回答by Joey Grimm
Here is a straight forward explanation to your question, which has helped me understand the difference between an attribute and a method.
这是对您的问题的直接解释,它帮助我理解了属性和方法之间的区别。
A class is like a set of instructions or blueprint for how to build many objects that share characteristics.
一个类就像一组指令或蓝图,用于构建许多共享特性的对象。
An object is a data type built according to specifications provided by the class definition.
对象是根据类定义提供的规范构建的数据类型。
An attribute is a value(characteristic). Think of an attribute as a variable that is stored within an object.
属性是一个值(特征)。将属性视为存储在对象中的变量。
A method is a set of instructions. Methods are functions, which are associated with an object. Any function included in the parent class definition can be called by an object of that class.
方法是一组指令。方法是与对象相关联的函数。父类定义中包含的任何函数都可以被该类的对象调用。
I hope this helps.
我希望这有帮助。
回答by Robai
An attribute describes an object whilst a method acts on an object and changes it.
一个属性描述一个对象,而一个方法作用于一个对象并改变它。