面向对象高级语法部分
- 经典类vs新式类
- 静态方法、类方法、属性方法
- 类的特殊方法
- 反射
经典类与新式类继承方式的区别
经典类:深度优先
新式类:广度优先
class A:
def __init__(self):
self.n = 'A'
class B(A):
# def __init__(self):
# self.n = 'B'
pass
class C(A):
def __init__(self):
self.n = 'C'
class D(B,C):
# def __init__(self):
# self.n = 'D'
pass
obj = D()
print(obj.n)
输出:C
静态方法的使用:
通过@staticmethod装饰器即可把其装饰的方法变为一个静态方法,什么是静态方法呢?其实不难理解,普通的方法,可以在实例化后直接调用,并且在方法里可以通过self.调用实例变量或类变量,但静态方法是不可以访问实例变量或类变量的,一个不能访问实例变量和类变量的方法,其实相当于跟类本身已经没什么关系了,它与类唯一的关联就是需要通过类名来调用这个方法;eat需要一个self参数,但调用时却没有传递,没错,当eat变成静态方法后,再通过实例调用时就不会自动把实例本身当作一个参数传给self了。
想让代码可以正常工作有两种办法
1. 调用时主动传递实例本身给eat方法,即d.eat(d)
2. 在eat方法中去掉self参数,但这也意味着,在eat中不能通过self.调用实例中的其它变量了
class Dog(object):
def __init__(self,name):
self.name = name
@staticmethod #把eat方法变为静态方法
def eat(self):
print("%s is eating" % self.name)
d = Dog("ln")
d.eat(d)
输出:
ln is eating
类方法的使用:
类方法通过@classmethod装饰器实现,类方法和普通方法的区别是, 类方法只能访问类变量,不能访问实例变量
class Dog(object):
name = 'hcl'
def __init__(self,name):
self.name = name
@classmethod
def eat(self):
print("%s is eating" % self.name)
d = Dog("ln")
d.eat()
输出:
hcl is eating
属性方法的使用:
class Dog(object):
def __init__(self,name):
self.name = name
self.__food = None
#@staticmethod
@property
def eat(self):
print("%s is eating %s" %(self.name,self.__food))
@eat.setter
def eat(self,food):
print("set to food:",food)
self.__food = food
@eat.deleter
def eat(self):
del self.__food
print("删除完毕")
d = Dog("hcl")
d.eat
d.eat = "ln"
d.eat
del d.eat
输出:
hcl is eating None
set to food: ln
hcl is eating ln
删除完毕
class Flight(object):
def __init__(self,name):
self.flight_name = name
def checking_status(self):
print("checking flight %s status " % self.flight_name)
return 1
@property
def flight_status(self):
status = self.checking_status()
if status == 0 :
print("flight got canceled...")
elif status == 1 :
print("flight is arrived...")
elif status == 2:
print("flight has departured already...")
else:
print("cannot confirm the flight status...,please check later")
@flight_status.setter #修改
def flight_status(self,status):
status_dic = {
0 : "canceled",
1 : "arrived",
2 : "departured"
}
print("Has changed the flight status to ",status_dic.get(status) )
@flight_status.deleter #删除
def flight_status(self):
print("status got removed...")
f = Flight("CA980")
f.flight_status
f.flight_status = 2 #触发@flight_status.setter
del f.flight_status #触发@flight_status.deleter
输出:
checking flight CA980 status
flight is arrived...
Has changed the flight status to departured
status got removed...
类的特殊成员方法:详细了解
#构造方法的执行是由创建对象触发的,即:对象 = 类名() ;而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()
class Foo:
def __init__(self):
print('__init__')
pass
def __call__(self, *args, **kwargs):
print ('__call__')
obj = Foo() # 执行 __init__
obj() # 执行 __call__
输出:
__init__
__call__
__dict__ 查看类或对象中的所有成员
class Province:
country = 'China'
def __init__(self, name, count):
self.name = name
self.count = count
def func(self, *args, **kwargs):
print ('func')
# 获取类的成员,即:静态字段、方法、
print (Province.__dict__)
# 获取 对象obj1 的成员
obj1 = Province('HeBei',10000)
print (obj1.__dict__)
obj2 = Province('HeNan', 3888)
print (obj2.__dict__)
输出:
{'__module__': '__main__', 'country': 'China', '__init__': <function Province.__init__ at 0x00000299C1FC1400>, 'func': <function Province.func at 0x00000299C2141488>, '__dict__': <attribute '__dict__' of 'Province' objects>, '__weakref__': <attribute '__weakref__' of 'Province' objects>, '__doc__': None}
{'name': 'HeBei', 'count': 10000}
{'name': 'HeNan', 'count': 3888}
__str__ 如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。
#如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。
class Foo:
def __str__(self):
return 'hcl'
obj = Foo()
print (obj)
输出:hcl
__getitem__、__setitem__、__delitem__
用于索引操作,如字典。以上分别表示获取、设置、删除数据
class Foo(object):
def __getitem__(self, key):
print('__getitem__',key)
def __setitem__(self, key, value):
print('__setitem__',key,value)
def __delitem__(self, key):
print('__delitem__',key)
obj = Foo()
result = obj['k1'] # 自动触发执行 __getitem__
obj['k2'] = 'hcl' # 自动触发执行 __setitem__
del obj['k1']
输出:
__getitem__ k1
__setitem__ k2 hcl
__delitem__ k1
类的两种创建方法:
def func(self):
print("hello %s"%self.name)
def __init__(self,name,age):
self.name = name
self.age = age
Foo = type('Foo',(object,),{'func':func,'__init__':__init__})
f = Foo("jack",22)
f.func()
输出:
hello jack
类的生成调用过程:
class MyType(type):
def __init__(self,*args,**kwargs):
print("Mytype __init__",*args,**kwargs)
def __call__(self, *args, **kwargs):
print("Mytype __call__", *args, **kwargs)
obj = self.__new__(self)
print("obj ",obj,*args, **kwargs)
print(self)
self.__init__(obj,*args, **kwargs)
return obj
def __new__(cls, *args, **kwargs):
print("Mytype __new__",*args,**kwargs)
return type.__new__(cls, *args, **kwargs)
print('here...')
class Foo(object,metaclass=MyType):
def __init__(self,name):
self.name = name
print("Foo __init__")
def __new__(cls, *args, **kwargs):
print("Foo __new__",cls, *args, **kwargs)
return object.__new__(cls)
f = Foo("hcl")
print("f",f)
print("fname",f.name)
输出:
here...
Mytype __new__ Foo (<class 'object'>,) {'__module__': '__main__', '__qualname__': 'Foo', '__init__': <function Foo.__init__ at 0x0000015DCBE11400>, '__new__': <function Foo.__new__ at 0x0000015DCBE11268>}
Mytype __init__ Foo (<class 'object'>,) {'__module__': '__main__', '__qualname__': 'Foo', '__init__': <function Foo.__init__ at 0x0000015DCBE11400>, '__new__': <function Foo.__new__ at 0x0000015DCBE11268>}
Mytype __call__ hcl
Foo __new__ <class '__main__.Foo'>
obj <__main__.Foo object at 0x0000015DCBC76080> hcl
<class '__main__.Foo'>
Foo __init__
f <__main__.Foo object at 0x0000015DCBC76080>
fname hcl
反射:
class Foo(object):
def __init__(self):
self.name = 'hcl'
def func(self):
return 'func'
obj = Foo()
# #### 检查是否含有成员 ####
print(hasattr(obj, 'name'))
print(hasattr(obj, 'func'))
# #### 获取成员 ####
print(getattr(obj, 'name'))
print(getattr(obj, 'func'))
# #### 设置成员 ####
print(setattr(obj, 'age', 18))
print(setattr(obj, 'show', lambda num: num + 1))
# #### 删除成员 ####
print(delattr(obj, 'name'))
print(delattr(obj, 'func'))
输出:
True
True
hcl
<bound method Foo.func of <__main__.Foo object at 0x0000019F6B9A9EF0>>
None
None
None
Traceback (most recent call last):
File "D:\F\eclipse-workspace\oop2\src\demo.py", line 32, in <module>
print(delattr(obj, 'func'))
AttributeError: func
六、有兴趣接电子设计相关小型项目的请加下群,每个项目一般在1000元以内,非诚勿扰