跳转至

🔥AI副业赚钱星球

点击下面图片查看

郭震AI

讨论很容易混淆的两种方法:静态方法和类方法,希望通过这篇文章大家了解更加深刻一些。

静态方法

在类中的方法前面通过@staticmethod装饰器即可把其装饰的方法变为一个静态方法

class Person(object):

    def __init__(self, name):
        self.name = name

    @staticmethod
    def speak():
        print('someone is speaking chinese.')

# 静态方法在类中也不需要传入 self参数

静态方法的特性

静态方法是不能访问实例变量和类变量的 

class Person(object):

    def __init__(self, name):
        self.name = name

    @staticmethod
    def speak(self):
        print('%s is speaking chinese.' % self.name)

p = Person('Bigberg')
p.speak()
# 我们在 speak(self) 函数中传入 self

事实上以上代码运行会出错的,说speak 需要一个self参数,但调用时却没有传递,没错,当speak变成静态方法后,再通过实例调用时就不会自动把实例本身当作一个参数传给self了。

Traceback (most recent call last):
  File "G:/python/untitled/study6/静态方法.py", line 26, in <module>
    p.speak()
TypeError: speak() missing 1 required positional argument: 'self'

想让以上代码可以正常执行,有两种方法:

第一种:在调用时将实例本身传给 speak() 

class Person(object):

    def __init__(self, name):
        self.name = name

    @staticmethod
    def speak(self):
        print('%s is speaking chinese.' % self.name)

p = Person('Bigberg')
p.speak(p)

# 输出

Bigberg is speaking chinese.

第二种:在方法speak中去掉self,但这也意味着,在eat中不能通过self.调用实例中的其它变量了 

class Person(object):

    def __init__(self, name):
        self.name = name

    @staticmethod
    def speak():                # 方法中已经没有 self 参数了
        print('%s is speaking chinese.' % 'anyone')

p = Person('Bigberg')
p.speak()
#输出
anyone is speaking chinese.

普通的方法,可以在实例化后直接调用,并且在方法里可以通过self.调用实例变量或类变量,但静态方法是不可以访问实例变量或类变量的,一个不能访问实例变量和类变量的方法,其实相当于跟类本身已经没什么关系了,它与类唯一的关联就是需要通过类名来调用这个方法。

类方法

通过@classmethod装饰器实现,类方法和普通方法的区别是, 类方法只能访问类变量,不能访问实例变量。

直接访问实例变量会报错,没有该属性  

class Person(object):

    def __init__(self, name, country):
        self.name = name
        self.country = country

    @classmethod
    def nationality(self):
        print('Bigberg is %s.' % self.country)

p = Person('Bigberg', 'CN')
p.nationality()

# 输出
Traceback (most recent call last):
  File "G:/python/untitled/study6/静态方法.py", line 31, in <module>
    p.nationality()
  File "G:/python/untitled/study6/静态方法.py", line 24, in nationality
    print('Bigberg is %s.' % self.country)
AttributeError: type object 'Person' has no attribute 'country'

# 提示没有一个 country 属性  

访问类变量

class Person(object):

    country = 'Chinese'    # 增加一个类属性

    def __init__(self, name, country):

        self.name = name
        self.country = country

    @classmethod
    def nationality(cls):    # 这里将sefl 改为 cls
        print('Bigberg is %s.' % cls.country)

p = Person('Bigberg', 'CN')
p.nationality()

# 输出
Bigberg is Chinese.

以上就是类方法和静态方法的区别,大家理解区分开了吗?有问题可以留言讨论。

大家在看

京ICP备20031037号-1 | AI之家 | AI资讯 | Python200 | 数据分析