根据我的理解,Python中对象的数据成员称为'属性'。
可调用的属性称为对象'方法'但是我无法找到不可调用属性的名称,例如以下示例中的val
:
class C:
def __init__(self):
self.val = 42. # How would this be called?
def self.action():
"""A method."""
print(self.val)
我相信不同的人可能会拨打val
不同的内容,例如' field'或者'变量'但我对正式名称感兴趣。
答案 0 :(得分:0)
我不确定是否存在,但我建议只使用“实例属性”。
有关此命名的功能:
class Container:
def __init__(self, item):
self.item = item
c = Container(x)
c.item # is an "instance attribute"
c.item == x # True
请注意,c.item
是一个“实例属性”,无论是否可以调用。我认为这是你所追求的行为,但我不确定。
class SomeClass:
x = 5 # Is not an "instance attribute"
obj.x = 5
obj.x # Is an "instance attribute"
最后,所有这些功能可能都是正面或负面的,具体取决于具体你想要什么。但我不知道你想要什么,这是我能得到的尽可能接近。如果您能提供更多信息,我可以给出更好的建议。
答案 1 :(得分:0)
令人惊讶地很难找到有关此主题的官方信息。在阅读this文章后,我相信应该将其简称为Class Variable
和Instance Variable
。
Attribute
是三个名称Property
,Method
和Variable
的集合名称。后两个前缀为Class
或Instance
。 property
只能属于Class
。
class Foo:
a = 1
def __init__(self):
self.b = 2
@property
def c(self):
return 3
@classmethod
def d(cls):
return 4
def e(self):
return 5
Foo.a # Class Attribute: Class Variable
Foo().a # Class Attribute: Class Variable
Foo().b # Instance Attribute: Instance Variable
Foo.c # Class Attribute: Property
Foo.d # Class Attribute: Class Method
Foo().d # Class Attribute: Class Method
Foo.e # Class Attribute: Class Method
Foo().e # Instance Attribute: Instance Method
来源
在Creately中制作的图表