1、定义
class Animal():
def __init__(self, __color, footNum, isCanSpeak):
"""
动物属性
:param color:
:param footNum:
:param isCanSpeak:
"""
self.__color = __color
self.footNum = footNum
self.isCanSpeak = isCanSpeak
self.isPersonFriend = True
2、继承
普通继承:
class Dog(Animal):
def __init__(self, __color, footNum, isCanSpeak, eyeNum):
super().__init__(__color, footNum, isCanSpeak)
接口继承(子类必须包含父类所有的实现):
class 接口类名(metaclass=abc.ABCMeta):
isTest = True
def __init__(self, school, money):
self.school = school
self.__money = money
@abc.abstractmethod
def hitStudent(self):
pass
3、类的特殊属性
print(Dog.__name__) #Dog 类名
print(Dog.__doc__) #None
print(Dog.__base__) #<class 'animal.Animal'> 第一个父类
print(Dog.__bases__) #(<class 'animal.Animal'>,) 所有父类
print(Dog.__dict__) #{'__module__': '__main__', '__init__': <function Dog.__init__ at 0x000001474D916730>, '__doc__': None}
print(dog.__module__) #__main__ 类定义所在模块
print(dog.__class__) #<class '__main__.Dog'>
print(dog.getColor()) #yellow
print(animal.__dict__["getColor"](dog))#yellow
print(vars(dog)) #{'_Animal__color': 'yellow', 'footNum': 4, 'isCanSpeak': False, 'isPersonFriend': True}
print(dir(dog)) #所有方法:['_Animal__cologetIsCanSpeak', 'isCanSpeak', 'isPersonFriend', 'setColor']
补充:
实例能访问类属性(因为实例在类的作用域中),类不能访问实例属性;
实例只有数据属性,没有函数属性;
4、类属性
#查看类属性
print(Animal.country)
#修改类属性
Animal.country = "Japan"
#删除类属性
del Animal.country
#增加类属性
Animal.loaction = "Asia"
print(Animal.__dict__)
5、实例属性
# 查看实例属性
print(dog.isCanSpeak)
# 增加实例属性
dog.name = "mengmeng"
# 删除实例属性
del dog.name
# 修改实例属性
dog.isCanSpeak = True
来源:https://www.cnblogs.com/chqworkhome/p/10954777.html