1、成员
1.1 变量
- 实例变量,属于对象,每个对象中各自维护自己的数据。
- 类变量,属于类,可以被所有对象共享,一般用于给对象提供公共数据(类似于全局变量)。
class Person(object): country = "中国" def __init__(self, name, age): self.name = name self.age = age def show(self): # message = "{}-{}-{}".format(Person.country, self.name, self.age) message = "{}-{}-{}".format(self.country, self.name, self.age) print(message) print(Person.country) # 中国 p1 = Person("华青水上",20) print(p1.name) print(p1.age) print(p1.country) # 中国 p1.show() # 中国-华青水上-20
提示:当把每个对象中都存在的相同的示例变量时,可以选择把它放在类变量中,这样就可以避免对象中维护多个相同数据。
易错点
- 注意读和写的区别。
class Person(object): country = "中国" def __init__(self, name, age): self.name = name self.age = age def show(self): message = "{}-{}-{}".format(self.country, self.name, self.age) print(message) print(Person.country) # 中国 p1 = Person("华青水上",20) print(p1.name) # 华青水上 print(p1.age) # 20 print(p1.country) # 中国 p1.show()<strong style="color:transparent">本文来源gaodai#ma#com搞@@代~&码网^</strong> # 中国-华青水上-20 p1.name = "root" # 在对象p1中讲name重置为root p1.num = 19 # 在对象p1中新增实例变量 num=19 p1.country = "china" # 在对象p1中新增实例变量 country="china" print(p1.country) # china print(Person.country) # 中国
class Person(object): country = "中国" def __init__(self, name, age): self.name = name self.age = age def show(self): message = "{}-{}-{}".format(self.country, self.name, self.age) print(message) print(Person.country) # 中国 Person.country = "美国" p1 = Person("华青水上",20) print(p1.name) # 华青水上 print(p1.age) # 20 print(p1.country) # 美国
- 继承关系中的读写
class Base(object): country = "中国" class Person(Base): def __init__(self, name, age): self.name = name self.age = age def show(self): message = "{}-{}-{}".format(Person.country, self.name, self.age) # message = "{}-{}-{}".format(self.country, self.name, self.age) print(message) # 读 print(Base.country) # 中国 print(Person.country) # 中国 obj = Person("华青水上",19) print(obj.country) # 中国 # 写 Base.country = "china" Person.country = "泰国" obj.country = "日本"
1.2 方法
- 绑定方法,默认有一个self参数,由对象进行调用(此时self就等于调用方法的这个对象)【对象&类均可调用】
- 类方法,默认有一个cls参数,用类或对象都可以调用(此时cls就等于调用方法的这个类)【对象&类均可调用】
- 静态方法,无默认参数,用类和对象都可以调用。【对象&类均可调用】
class Foo(object): def __init__(self, name,age): self.name = name self.age = age def f1(self): print("绑定方法", self.name) @classmethod def f2(cls): print("类方法", cls) @staticmethod def f3(): print("静态方法") # 绑定方法(对象) obj = Foo("武沛齐",20) obj.f1() # Foo.f1(obj) # 类方法 Foo.f2() # cls就是当前调用这个方法的类。(类) obj.f2() # cls就是当前调用这个方法的对象的类。 # 静态方法 Foo.f3() # 类执行执行方法(类) obj.f3() # 对象执行执行方法