python:当类属性、实例属性和方法都具有相同的名称时会发生什么? [英] python: What happens when class attribute, instance attribute, and method all have the same name?

查看:30
本文介绍了python:当类属性、实例属性和方法都具有相同的名称时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python如何在名称相同的情况下区分类属性、实例属性和方法?

How does python differentiate a class attribute, instance attribute, and method when the names are the same?

class Exam(object):

    test = "class var"

    def __init__(self, n):
        self.test = n

    def test(self):
        print "method : ",self.test

test_o = Exam("Fine")

print dir(test_o)

print Exam.test
print test_o.test
test_o.test()

输出:

['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__',    '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'test']
<unbound method load.test>
Fine
Traceback (most recent call last):
  File "example.py", line 32, in <module>
    test_o.test()
TypeError: 'str' object is not callable

如何调用

  1. class 属性,Exam.test --> 输出显示方法
  2. 实例属性 test_o.test --> "Fine"
  3. method test_o.test() --> TypeError: 'str' object is not callable
  1. class attribute, Exam.test --> <unbound method load.test> output shows method
  2. instance attribute test_o.test --> "Fine"
  3. method test_o.test() --> TypeError: 'str' object is not callable

推荐答案

类属性可通过类访问:

YourClass.clsattribute

或者通过实例(如果实例没有覆盖类属性):

or through the instance (if the instance has not overwritten the class attribute):

instance.clsattribute

方法,如 ecatmur 在他的回答中所述,是描述符并被设置为类属性.

Methods, as stated by ecatmur in his answer, are descriptors and are set as class attributes.

如果您通过实例访问方法,则该实例将作为 self 参数传递给描述符.如果你想从类中调用一个方法,那么你必须显式地传递一个实例作为第一个参数.所以这些是等价的:

If you access a method through the instance, then the instance is passed as the self parameter to the descriptor. If you want to call a method from the class, then you must explicitly pass an instance as the first argument. So these are equivalent:

instance.method()
MyClass.method(instance)

对实例属性和方法使用相同的名称会使方法通过实例隐藏,但方法仍然可以通过类使用:

Using the same name for an instance attribute and a method will make the method hidden via the instance, but the method is still available via the class:

#python3
>>> class C:
...     def __init__(self):
...         self.a = 1
...     def a(self):
...         print('hello')
... 
>>> C.a
<function a at 0x7f2c46ce3c88>
>>> instance = C()
>>> instance.a
1
>>> C.a(instance)
hello

结论:不要给实例属性和方法同名.我通过给出有意义的名字来避免这种情况.方法就是动作,所以我通常用动词或句子来表示它们.属性是数据,所以我用名词/形容词来表示它们,这样可以避免对方法和属性使用相同的名称.

Conclusion: do not give the same name to instance attributes and methods. I avoid this by giving meaningful names. Methods are actions, so I usually use verbs or sentences for them. Attributes are data, so I use nouns/adjectives for them, and this avoids using the same names for both methods and attributes.

请注意,您根本不能拥有与方法同名的类属性,因为该方法会完全覆盖它(最后,方法只是可调用的类属性,并且会自动接收类的实例作为第一个属性).

Note that you simply cannot have a class attribute with the same name as a method, because the method would completely override it (in the end, methods are just class attributes that are callable and that automatically receive an instance of the class as first attribute).

这篇关于python:当类属性、实例属性和方法都具有相同的名称时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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