1. class
class Person:
'人的基类'
perCount=0
def __init__(self, name, gender, age):
self.name=name
self.gender=gender
self.age=age
Person.perCount +=1
def displayCount(self):
print("Totoal Employee %d",Person.perCount)
def displayEmployee(self):
print("Name: ", self.name, ", age: ", self.age)
#Python内置类属性
print("Person.__doc__:" , Person.__doc__)#类的文档字符串
print("Person._name_:", Person.__name__)#类名
print("Person.__module__:",Person.__module__)#类定义所在的模块(类的全名是'__main__.className',如果类位于一个导入模块mymod中,那么className.__module__ 等于 mymod)
print("Person.__bases__", Person.__bases__)#类的所有父类构成元素(包含了一个由所有父类组成的元组)
print("Person.__dict__:", Person.__dict__)# 类的属性(包含一个字典,由类的数据属性组成)
emp1=Person("Zara","female",18)
emp2=Person("Mi","male",18)
emp1.displayEmployee()
/Users/xxx/PycharmProjects/xxx/venv/bin/python /Users/xxx/PycharmProjects/xxx/ceshi.py
Person.__doc__: 人的基类
Person._name_: Person
Person.__module__: __main__
Person.__bases__ (<class 'object'>,)
Person.__dict__: {'__module__': '__main__', '__doc__': '人的基类', 'perCount': 0, '__init__': <function Person.__init__ at 0x108bcce18>, 'displayCount': <function Person.displayCount at 0x108bccd08>, 'displayEmployee': <function Person.displayEmployee at 0x108bccea0>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>}
Name: Zara , age: 18
Process finished with exit code 0
self表示类的实例,非类本身。
2. inherit
class Person:
'人的基类'
def __init__(self, name, gender, age):
self.name=name
self.gender=gender
self.age=age
def modifyAttri(self,attri):
self.attri=attri
print("Attri: ",self.attri)
class Female(Person):
'女性类'
def __init__(self,hobby):
self.hobby=hobby
print("hobby: ",self.hobby)
def getFamilyInfo(self):
print("Ten members in hers family.")
c=Female("swimming")#实例化一个对象
c.getFamilyInfo()#调用子类方法
c.modifyAttri("SWIMING")#调用父类方法
hobby: swimming
Ten members in hers family.
Attri: SWIMING
Process finished with exit code 0
下面看下子类调用父类构造方法:
3. override
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/18726.html