Python 面向对象之类成员
类成员:
1.字段:普通字段、静态字段
普通字段,保存在对象中
静态字段,保存在类中
1 class Province: 2 #静态字段,属于类 3 country='中国' 4 def __init__(self,name): 5 #普通字段,属于对象 6 self.name=name 7 henan=Province('河南') 8 hebei=Province('河北') 9 print(Province.country)#中国 10 print(henan.name)#河南 11 print(Province.name)#AttributeError: type object 'Province' has no attribute 'name'
普通字段访问方式为 对象.普通字段名
类字段访问方式为 类.静态字段名 对象.静态字段名
使用 对象.静态字段可以访问,但是使用 类.普通字段 不可以访问
2.方法:普通方法、静态方法、类方法
普通方法,保存在类中,可以使用对象.方法调用,可以使用类.方法调用(需要传递对象参数),必须传递对象self
静态方法,保存在类中,使用类.方法调用,不用传递对象,可以任意传递参数,也可不传参数
类方法,保存在类中,使用 类.方法调用,默认传递类名cls
1 class Foo: 2 #普通方法,默认参数为对象 3 def foo(self): 4 print('bar') 5 #静态方法,可以任意传递参数 6 @staticmethod 7 def foo1(a,b): 8 print(a,b) 9 #类方法,默认参数为类名 10 @classmethod 11 def foo2(cls): 12 print('bar2') 13 #调用普通方法 14 f=Foo() 15 f.foo() 16 17 Foo.foo(f) 18 #调用静态方法 19 Foo.foo1(1,2) 20 #调用类方法 21 Foo.foo2()
应用场景
普通方法:如果对象中需要保存一些值,执行某功能时需要使用对象中的值
静态方法(类方法):不需要任何对象中的值
3.属性
以方法形式来定义,以字段形式来调用
方式一
1 class Foo: 2 #属性用于获取值 3 @property 4 def per(self): 5 print('bar3') 6 return 1 7 #属性用于赋值操作 8 @per.setter 9 def per(self,val): 10 print('bar4') 11 print(val) 12 #属性用于删除操作 13 @per.deleter 14 def per(self): 15 print('bar5') 16 f=Foo() 17 18 print(f.per) 19 f.per=123 20 del f.per
方式二
1 class Person(object): 2 def f1(self): 3 print(1) 4 def f2(self,val): 5 print(2) 6 def f3(self): 7 print(3) 8 #将f与f1,f2,f3绑定 9 f=property(fget=f1,fset=f2,fdel=f3) 10 p=Person() 11 p.f 12 p.f=123 13 del p.f
浙公网安备 33010602011771号