python_面向对象——类方法和静态方法

1.类方法不能访问实例变量,只能访问类变量。

class Dog(object):
    name = 'wdc'
    def __init__(self,name):
        self.name = name

    def eat(self):  #普通方法
        print(self)
        print('{}在吃东西~'.format(self.name))

    @classmethod    #类方法
    def eatt(self):
        print(self) #打印self发现传进来的self不是实例本身,而是类本身
        print('{}在吃东西'.format(self.name))

a = Dog('yhf')
a.eat()
a.eatt()

 2.类方法的应用

class Dog(object):
    dog_num = 0
    def __init__(self,name):
        self.name = name
        self.__add_dog(self)  #实例化时调用类方法add_dog,可以将实例化的对象传递进入类方法

    @classmethod
    def __add_dog(cls,obj):
        cls.dog_num += 1
        print('生成一只狗:{},共{}只狗'.format(obj.name,cls.dog_num))

a1 = Dog('yhf1')
a2 = Dog('yhf2')
a3 = Dog('yhf3')

 3.静态方法

  :不能访问类变量,也不能访问实例变量

class Student(object):
    def __init__(self,name):
        self.name = name

    @staticmethod
    def fly():
        print('fly...')

    @staticmethod
    def walk(self):
        print('{} walking...'.format(self.name))


a = Student('wdc')
a.fly()
a.walk(a)   #静态方法必须自己传递对象参数

原文地址:https://www.cnblogs.com/wangdianchao/p/11957130.html