首页 > 编程 > Python > 正文

Python自学笔记三、面向对象编程2

2019-11-09 20:22:31
字体:
来源:转载
供稿:网友

1.再谈反射:

class Foo(): def __init__(self,name): self.name=name def show(self): PRint 'show'obj=Foo('alex')o=hasattr(Foo,'show')print oo1=hasattr(Foo,'name')print o1r=hasattr(obj,'name')print rs=hasattr(obj,'show')print s#True#False#True#True

前文讲过反射是以字符串的形式去对象中操作成员,根据上面的代码看来类只能找类里的成员;而对象既可以找到自己的成员也可以找类的成员。

2.成员

class Foo: #静态字段 position='China' #构造法方法 def __init__(self,name): temp='xxx' #普通字段,存在对象中 self.name=name #静态方法,可以通过类访问 @staticmethod def xo(arg1):#可以没有参数 print 'xo' print'arg' Foo.xo('123') #xo #123 #普通方法,存在类中 def show(self): print 'show' #类方法,通过类进行访问 @classmethod def xxoo(cls):#必须要有cls print ('xxoo',cls)Foo.xxoo()#将当前类的类名传入#('xxoo', <class __main__.foo at 0x020A9CA8>) #特性,将方法伪装成一种字段 @property def start(self):#不能传额外的参数 temp='%s ' %self.name return temp def end(self): temp='%s ' %self.name return temp obj=Foo('peter') return1=obj.end() print return1 return2=obj.start #未加括号 print return2#peter#peter

综上所述:类的成员中包括静态字段,普通字段,静态方法,普通方法,类方法,特性。 其中通过类访问的有:静态字段,静态方法、类方法。 通过对象方有的有:普通字段、普通方法和特性

静态字段:存在类中 ,静态字段存在的意:把对象里面重复的数据只在类里保存一份。 普通字段,存放在对象中。 普通方法必须创建对象后才可以调用。 静态方法不需要先创建对象就可以调用,它只是写来类里的一个函数,跟对象无关,通过类直接访问,支持函数式编程。 类方法可通过类直接访问,带有的必须参数是当前类的类名,无需建立对象。 特性是对象来调用的,原来以函数的访问方式(函数后加括号)改成以字段的形式来访问,此时该函数不能添加参数。

3.成员修饰符

全局变量(公有成员):任何对象都能访问。 局部变量(私有成员):只有在类的内部才能访问,定义方式为命名时,加入下划线。

class Person: contry='China' #静态字段,属于全局变量 __provice='HuBei' #局部变量,属于私有变量 def __init__(self,name): self.name=name def get_person_arg(self): print (Person.__provice)print (Person.__provice)#AttributeError: class Person has no attribute '__provice'#不能访问私有变量p=Person('peter')print p.__provice#AttributeError: Person instance has no attribute '__provice'#类实例也不能访问私有变量p=Person('peter')p.get_person_arg()#HuBei#通过类的方法获取私有变量

那么Person的子类能够访问他的私有变量吗?

class A: def __init__(self,name): self.__name='alex' def get_arg(self): print self.__nameclass B(A): def get_arg(self): print self.__nameb=B()b.get_arg()#AttributeError: B instance has no attribute '_B__name'#创建b实例时,执行父类的构造函数,但是__name为A类的私有变量,并不能继承,所以错误中提示B类并没有__name变量。

所以,私有变量(函数)只有自己能访问,其他父类子类都不行。

4.类的特殊成员

class A: def __init__(self): print 'init' def __call__(self,*args,**kwargs): print 'call'a=A()a()#init#call类后面加括号执行__init__对象后面加括号执行__call__

doc:表示类的描述信息 module:当前操作的对象在哪个模块. class:表示当前操作对象的类是什么 init:构造方法,创建对象时自动触发 call:对象后面加括号,触发执行 dict:类或对象中的所有成员 str:如果一个类中定义了str方法,那么在打印对象时,默认输出该方法的返回值。 setitem,getitem,delitem,用于索引操作,如字典。分别表示获取,设置,删除数据。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表