python 类方法 静态方法

属性:函数

  公有属性  (属于类,每一个类一份)spa

  普通属性  (属于对象,每一个对象一份)code

  私有属性    (属于对象,跟普通属性类似,只是不能经过对象直接访问) 对象

方法:(按做用)blog

  构造方法it

  析构函数class

方法:(按类型)变量

  普通方法object

  私有方法(方法前面加两个下划线)方法

  静态方法

  类方法

  属性方法

静态方法

@staticmethod
静态方法,经过类直接调用,不须要建立对象,不会隐式传递self

类方法

@classmethod
类方法,方法中的self是类自己,调用方法时传的值也必须是类的公有属性,
就是说类方法只能操做类自己的公有字段

class Dog(object): food = "gutou" age = "1"
    def __init__(self, name): self.NAME = name @classmethod def eat(self,age): #只能是类中的变量
        # print(self.NAME)
        print(age) print(self.food) @classmethod def eat1(self, age):  # 只能是类中的变量
        # print(self.NAME)
        age = "2" self.food = "tang" @staticmethod def print_1(): print(Dog.food, Dog.age) d = Dog("labuladuo") d.eat(Dog.age) #经过对象调用
Dog.eat(Dog.age)  #经过类调用
print("-----1-----") d.eat1(Dog.age) Dog.print_1() print("--------2-------") Dog.eat1(Dog.age) Dog.print_1()

output:

1gutou1gutou-----1-----('tang', '1')--------2-------('tang', '1')

相关文章
相关标签/搜索