![](/img/trans.png)
[英]Check if instance of python class has attribute without instantiating the class
[英]Python - Instantiating a class without assigning a name to the instance
Python 新手在这里!
下面的示例是关于实例化 class 然后为实例分配名称与不分配实例化之间的区别。
在示例的最后三行中,首先在实例 (my_city) 上调用该方法,然后在没有实例的情况下调用该方法。 所以:
class City:
def __init__(self, name):
self.name = name
def show_city_name(self):
print(self.name)
my_city = City("Tokyo")
my_city.show_city_name()
City("Tokyo").show_city_name()
City("Tokyo").show_city_name()
语句导致创建类型为<class '__main__.City'>
的临时实例,在该实例上调用show_city_name()
方法。
所以,实例仍然被创建,认为它没有与任何对它的引用绑定。 我们可以说 object 在City("Tokyo")
表达式中。 看看这个:
>>> type(City('Foo'))
<class '__main__.City'> # Means it is an instance of the City class
当您拥有static
class 方法或@classmethod
装饰器时,可以看到几乎相同类型的方法(看似直接在 class 上调用方法)。 例如:
class Circle:
def __init__(self, radius):
self.radius = radius
# other definitions
@classmethod
def unit_circle(cls):
return cls(1)
unit_c = Circle.unit_circle()
print(unit_c.radius)
# Prints 1
这是在现实世界代码中做同样事情的更正确和更有可能的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.