python中类的成员
成员有以下:
1、字段: 静态字段 普通字段
2、方法: 静态方法 类方法 普通方法
3、特性/属性 普通特性
成员修饰符 修饰成员
公有的:没有限制
私有的:以__开头 仅仅内部可以访问,不能被继承,仅自己可访问。私有的成员可通过公有的成员间接访问
何时用类调用,何时用对象调用?
类调用: 无self
对象调用:self
结论:
1、静态字段和静态方法和类方法通过类来访问,普通字段和方法通过对象来访问
2、静态方法,使用@staticmethod来装饰
3、类方法,使用@classmethod来装饰
4、属性(特性),使用@property来装饰,定义的时候类似普通方法一样,但调用的时候像普通字段一样
5、属性的getter和setter,通过@property来装饰的方法return来getter,之后通过@方法名.setter装饰的方法来setter
一些特殊的成员:
__init__ 构造方法,创建对象时调用
__del__ 析构方法,销毁对象时调用
__call__ 对象() 调用
__getitem__ 对象[] 来调用
__setitem__ 对象[] = xxx 来调用
__delitem__ del 对象[] 来调用
__dict__ 列出所有的成员 用途:在表单对象中获取表单所有的字段
参考字典对象dict
__str__ 类似java中的toString方法,直接打印对象输出的就是该方法的返回值
class Province: country = "中国" # 静态字段,在类中保存,将对象中共有的字段和值可以保存到静态字段 def __init__(self, name): self.name = name # 普通字段 @staticmethod def xxoo(arg1, arg2): # 静态方法 print(arg1, arg2) @classmethod def xo(cls): # 类方法 会将类传递过来 print(cls) @property def xx(self): # 属性(特性),将方法伪装成字段 getter # print("property") return self.val @xx.setter def xx(self, value): self.val = value hubei = Province("湖北") print(hubei.__dict__) print(Province("福建").__dict__) print(Province.__dict__) print(Province.country) # 静态字段通过类来访问 Province.xxoo("hello", "hi") # 静态方法通过类来访问 Province.xo() # 类方法通过类来访问 hubei.xx = "property1" # 属性的setter print(hubei.xx) #属性调用 getter
class Foo: xo = "xo" __ox = "__ox" def __init__(self): pass def fetch(self): print(Foo.__ox) # 私有的成员通过公有的成员间接访问 def __hello(self): print("__hello") @staticmethod def __dd(): print("__dd") def dd(self): self.__hello() Foo.__dd() def __call__(self, *args, **kwargs): print("call") def __getitem__(self, item): print(item, type(item)) def __setitem__(self, key, value): print(key,value) def __delitem__(self, key): print(key) def __iter__(self): yield 1 yield 2 yield 3 class Bar(Foo): def __init__(self): # self.__hello() # self.__ox # 父类私有的成员,子类不能访问 pass print(Foo.xo) # print(Foo.__ox) f = Foo() f.fetch() # f.__hello() f.dd() print(Bar.xo) b = Bar() b.dd() # f._Foo__hello() # 私有的普通字段或普通方法可通过该方式在外部访问,但不建议使用 f() # 调用__call__方法 f["abcd"] #调用__getitem__ f[1:6:2] #slice(1, 6, 2) <class 'slice'> 切片 __getitem__ 在py2.7 __getslice__ f["k1"] = "v1" #调用__setitem__ f[1:6:2] = ["a", "b", "c"] #slice(1, 6, 2) ['a', 'b', 'c'] 切片 __setitem__ 在py2.7 __setslice__ del f["k1"] print(f.__dict__) print(Foo.__dict__) for i in f: # 如果一个类实现了__iter__方法,其对象可以通过for来迭代 print(i)