这里先肯定的回答一下:可以
python里方法在类中是作为类的属性的,在解释之前,这边先给个例子
>>>class Pizza(object):... radius = 42
... def __init__(self, size=10):
... self.size = size
... def get_size(self):
... return self.size
... @staticmethod
... def mix_ingredients(x, y):
... return x + y
... def cook(self):
... return self.mix_ingredients(self.cheese, self.vegetables)
... @classmethod
... def get_radius(cls):
... return cls.radius
>>> Pizza.get_size
<unbound method Pizza.get_size>
>>> Pizza.get_size()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method get_size() must be called with Pizza instance as first argument (got nothing instead)
>>> Pizza.get_size(Pizza(42))
42
>>> Pizza(42).get_size
<bound method Pizza.get_size of <__main__.Pizza object at 0x7f3138827910>>
>>> Pizza(42).get_size()
42
>>> m = Pizza(42).get_size
>>> m()
42
>>> m = Pizza(42).get_size
>>> m.__self__
<__main__.Pizza object at 0x7f3138827910>
>>> m == m.__self__.get_size
True
>>> Pizza().cook is Pizza().cook
False
>>> Pizza().mix_ingredients is Pizza.mix_ingredients
True
>>> Pizza().mix_ingredients is Pizza().mix_ingredients
True
>>> Pizza.get_radius
<bound method type.get_radius of <class '__main__.Pizza'>>
>>> Pizza().get_radius
<bound method type.get_radius of <class '__main__.Pizza'>>
>>> Pizza.get_radius is Pizza().get_radius
True
>>> Pizza.get_radius()
42
在上面的例子中可以看出python中类有三种方法,分别是类方法,静态方法,实例方法。而能让类只接调用的只有类方法,或通过一些小技巧,类也可以调用实例方法如上面例子中的调用
>>> Pizza.get_size(Pizza(42))42
这边顺便说明下这三中方法的区别
1类方法的特点是类方法不属于任何该类的对象,只属于类本身
2类的静态方法类似于全局函数,因为静态方法既没有实例方法的self参数也没有类方法的cls参数,谁都可以调用
3.实例方法只属于实例,是实例化的对象才能调用
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)