python中可以直接用类调用方法吗

如题所述

这里先肯定的回答一下:可以

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.实例方法只属于实例,是实例化的对象才能调用

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-09-22
1、如果你需要用实例来调用你的方法,那么在定义方法的时候,一定要把第一个参数设置成为self;
2、如果你需要使用静态方法,那么你需要在方法前面加上@staticmethod修饰符;
3、如果要使用类方法,那么你需要在方法前面加上@classmethod修饰符,并且在方法中至少使用一个参数,第一个参数在方法中的作用就是代表改类本身。
第2个回答  2016-10-29
不可以
类是一个描述性的东西 不是一个具象的东西 它不能做任何事情 包括调用方法
类的实例才是一个具有行为能力的东西 因此只有实例化之后才能调用方法
相似回答