python面向对象基础知识学习
请参看慕课网视频:https://www.imooc.com/learn/747
我已经看过了,免费的,很基础,看完之后,需要自己消化学习
3-1 用Python定义类对应的代码实例:
class Newstyle(object):
def __init__(self,name,description):
self.name = name
self.description = description
if __name__ == '__main__':
new = Newstyle('new','New style class python 工程师')
print(new)
print(type(new))
print(dir(new))
3-2 Python面向对象-定义类的属性 对应的代码实例:
class Programer(object):
hobby = 'Study Python Class'
def __init__(self,name,age,weight):
self.name = name #公有属性
self._age = age #私有属性,可同对象不同类内访问
self.__weight = weight #私有属性,可同对象同类内访问
def get_weight(self):
return self.__weight
if __name__ == '__main__':
programer = Programer('Lucky','4.5','100cm') #对象实例化
print(dir(programer)) #打印对象属性
print(programer.__dict__) #打印对象中构造函数的属性
print(programer.get_weight()) #获取构造函数weight值
print(programer._Programer__weight) #获取构造函数weight值
3-3 Python面向对象-定义类的方法 对应的代码实例:
#常用的方法定义
class Example(object):
def add(self): #公有方法
pass
def _minus(self): #私有方法
pass
def __multiply(self):#私有方法
pass
#实例
class Programer(object):
hobby = 'Study Python Class'
def __init__(self,name,age,weight):
self.name = name #公有属性
self._age = age #私有属性,可同对象不同类内访问
self.__weight = weight #私有属性,可同对象同类内访问
@classmethod #调用时用类名,而不是某个对象,装饰器
def get_hobby(cls):
return cls.hobby
@property #像访问属性一样调用方法,装饰器
def get_weight(self):
return self.__weight
def self_introduction(self):
print ('My cat Name is %s \nIt is %s years old \n'%(self.name,self._age))
if __name__ == '__main__':
programer = Programer('Lucky','4.5','100cm') #对象实例化
print(dir(programer)) #打印对象属性
print(Programer.get_hobby()) #调用时用类名
#print(programer.__dict__) #打印对象中构造函数的属性
print(programer.get_weight) #获取构造函数weight值,访问方法,不需要括号()
#print(programer._Programer__weight) #获取构造函数weight值
programer.self_introduction()
3-4 Python面向对象-类的继承对应的代码实例:
#用super()调用父类的方法
class A(object):
def method(self,arg):
pass
class B(A):
def method(self,arg):
super(B,self).method(arg)
#用类名调用父类的方法
class A(object):
def method(self,arg):
pass
class B(A):
def method(self,arg):
A.method(arg)
#子类的类型判断
#isinstance 判断类型
#issubclass 判断是否子类
#实例
class Programer(object):
hobby = 'Study Python Class'
def __init__(self,name,age,weight):
self.name = name #公有属性
self._age = age #私有属性,可同对象不同类内访问
self.__weight = weight #私有属性,可同对象同类内访问
@classmethod #调用时用类名,而不是某个对象,装饰器
def get_hobby(cls):
return cls.hobby
@property #像访问属性一样调用方法,装饰器
def get_weight(self):
return self.__weight
def self_introduction(self):
print ('My cat Name is %s \nIt is %s years old \n'%(self.name,self._age))
class BackendProgramer(Programer):
def __init__(self,name,age,weight,language):
super(BackendProgramer,self).__init__(name,age,weight)
self.language = language
if __name__ == '__main__':
#programer = Programer('Lucky','4.5','100cm') #对象实例化
programer = BackendProgramer('Lucky','4.5','100cm','Cat self Language')
print(dir(programer)) #打印对象属性
#print(Programer.get_hobby()) #调用时用类名
print(programer.__dict__) #打印对象中构造函数的属性
print(type(programer)) #打印类的种类
print(isinstance(programer,Programer)) # 判断programer这个类的父类是不是Programer
3-5 类的多态对应的代码实例:
#多态要素
#1.继承;2.方法重写
#实例
class Programer(object):
hobby = 'Study Python Class'
def __init__(self,name,age,weight):
self.name = name #公有属性
self._age = age #私有属性,可同对象不同类内访问
self.__weight = weight #私有属性,可同对象同类内访问
@classmethod #调用时用类名,而不是某个对象,装饰器
def get_hobby(cls):
return cls.hobby
@property #像访问属性一样调用方法,装饰器
def get_weight(self):
return self.__weight
def self_introduction(self):
print ('My cat Name is %s \nIt is %s years old \n'%(self.name,self._age))
class BackendProgramer(Programer):
def __init__(self,name,age,weight,language):
super(BackendProgramer,self).__init__(name,age,weight)
self.language = language
def self_introduction(self):
print ('My cat Name is %s \nIts favorite language is %s \n'%(self.name,self.language))
def introduce(programer):
if isinstance(programer,Programer):#判断programer是否为Programer的子类,是则打印BackendProgramer中self_introduction
programer.self_introduction()
if __name__ == '__main__':
programer = Programer('Lucy','25','160cm') #对象实例化
backend_programer = BackendProgramer('Lucky','4.5','100cm','Cat self Language')
introduce(programer)
introduce(backend_programer)
#print(dir(programer)) #打印对象属性
print(Programer.get_hobby()) #调用时用类名
4-2 对象的实例化对应的代码实例:
#对象的实例化
#创建类的对象 ----> 初始化对象
#def__new__(cls) def__init__(self)
#回收对象
#__del__()
#实例
class Programer(object):
def __new__(cls, *args, **kwargs):#重写new方法
print ('call__new__method')
print(args)
#return super(Programer,cls).__new__(cls, *args, **kwargs) #运行会报错,object无参数。则返回值中不应传入空值*args,**kwargs
return super(Programer,cls).__new__(cls)#用super()调用父类的new方法返回Programer对象
def __init__(self,name,age):#设置Programer对象
print('call__init__method')
self.name = name
self.age = age
if __name__ == '__main__':
programer = Programer('Albert',25)
print(programer.__dict__) #打印对象中构造函数的属性
注意事项:
return super(Programer,cls).new(cls, *args, **kwargs) #慕课网上老师是使用的这个return打印出来,没有报错,可我运行后就报错了,object无参数。
出现的问题:
解决的方法:
网上的解决方法为:
1、 init方法左右的下划线只写了一个
2、 init方法写成int了。
可我发现我的代码中这两个问题都不存在,当时就蒙蔽了,后来print了args和**kwargs两个参数,发现args和kwargs为空值,则class的返回值不能传入空值;则修改了return代码,去掉了*args和kwargs两个参数,运行后就正确了;和老师运行结果一致;如图所诉:
4-3 类与运算符对应的代码实例:
#类与运算符
#比较运算符
# __cmp__(self,other) #包含所有的比较情况
# __eq__(self,other) #包含等于情况
# __lt__(self,other) #包含小于情况
# __gt__(self,other) #包含大于情况
#数字运算符
# __add__(self,other) #加法
# __sub__(self,other) #减法
# __mul__(self,other) #乘法
# __div__(self,other) #除法
#逻辑运算符
# __or__(self,other) #判断语句中,判断或
# __and__(self,other) #判断语句中,判断与
#实例
class Programer(object):
def __init__(self,name,age):
self.name = name
if isinstance(age,int):#判断age是否为int型
self.age = age
else:
raise Exception('age must be int !!!')
def __eq__(self, other):
if isinstance(other,Programer):#判断other是不是Programer类型的对象
if self.age == other.age:#判断两个类的age是否相等
return True
else:
return False
else:
raise Exception('The type of object must be Programer !!!')
def __add__(self, other):
if isinstance(other,Programer):
return self.age + other.age
else:
raise Exception('The type of object must be Programer !!!')
if __name__=='__main__':
p1 = Programer('Albert',25)
p2 = Programer('Bill',25)
print( p1 == p2)
print( p1 + p2)
4-4 类的展现对应的代码实例:
#类的展现
#转化为字符串
# __str__ 适合用户识别的字符串,eval函数不会把__str__转化的字符串作为python代码运行
# __repr__ 适合机器识别的字符串,eval函数会把__repr__转化的字符串作为python代码运行
# __unicode__
#展现对象属性
#__dir__
#实例
class Programer(object):
def __init__(self,name,age):
self.name = name
if isinstance(age,int):#判断age是否为int型
self.age = age
else:
raise Exception('age must be int !!!')
def __str__(self):
return '%s is %s years old !!!'%(self.name,self.age)
def __dir__(self):
return self.__dict__.keys()
if __name__=='__main__':
p = Programer('Albert',25)
print(p)
print(p.__dict__)
print(dir(p))
4-5 类的属性访问对应的代码实例:
#类的属性访问
#设置对象属性
#__setattr__(self,name,value) 调用从父类继承的方法
#注意事项
# def __setattr__(self,name,value): #错误写法
# setattr(self,name,value) #内置的setattr , 导致无限递归,递归超过1000次,程序报错
# def __setattr__(self,name,value):#正确写法
# self.__dict__[name] = value #避免了无限递归
#查询对象属性
# __getattr__(self,name): 访问这个属性默认未查询的情况下,才会调用该方法查询对象属性
# __getattribute__(self,name):每次访问时,都会调用该方法查询对象属性,容易引起无限递归的情况
#删除对象属性
# __detattr__(self,name):
#实例
class Programer(object):
def __init__(self,name,age):
self.name = name
self.age = age
def __getattribute__(self, name):
#return getattr(self,name) #报错‘maximum recursion depth exceeded’
#return self.__dict__[name]#报错‘maximum recursion depth exceeded’
return super(Programer,self).__getattribute__(name)#调用父类的getattribute,不会出现无限递归
def __setattr__(self, name, value):
#setattr(self, name, value) #报错‘maximum recursion depth exceeded’
self.__dict__[name] = value
if __name__=='__main__':
p = Programer('Albert',25)
print(p.name)