类
类名称的首字母要大写
类中__init__()方法在创建实例时自动运行。
self对应实例的名称,不同的实例有不同的属性和方法。
class Dog():
def __init__(self, name, age):
self.name = name
self.age = age
def sit(self):
print(self.name.title() + " is now sitting.")
def roll_over(self):
print(self.name.title() + " rolled over!")
类的继承
通过super()函数继承。
class Car():
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name="{} {} {}".format(self.year,\
self.make,self.model)
return long_name.title()
class ElectricCar(Car):
def __init__(self, make, model, year):
super().__init__(make, model, year)
open/closed_principle:Software entities should be open for extension, but closed for modification.
另外两种继承方式:
pass原样照搬
class Person:
def __init__(self,name,sex):
self.name = name
self.sex = sex
def print_title(self):
if self.sex == "male":
print("man")
elif self.sex == "female":
print("woman")
class Child(Person):
pass
用父类名字继承
class Person:
def __init__(self,name,sex):
self.name = name
self.sex = sex
def print_title(self):
if self.sex == "male":
print("man")
elif self.sex == "female":
print("woman")
class Child(Person):
def __init__(self,name,sex):
Person.__init__(self,name,sex)
三种继承方式在单个的继承中没有区别,在多重继承中有区别
多重继承:一个子类有多个父类,较为复杂,使用super()可以确定关系。
判断实例、判断类的父子关系的函数:
class Person:
pass
class Child(Person):
pass
May = Child()
Peter = Person()
print(isinstance(May,Child)) # True
print(isinstance(May,Person)) # True
print(isinstance(Peter,Child)) # False
print(isinstance(Peter,Person)) # True
print(issubclass(Child,Person)) # True
__xxx__
所有类,包括列表,字典,字符串以及自定义的类等,都继承于object类,它是一个最基础的类。
class A:与classA(object):是等价的。
__xxx__型的函数规定一些底层的运算规则,在创建类时也可以修改。
class Dog():
"This is about dog class."
def __init__(self, name, age):
self.name = name
self.age = age
print(Dog.__doc__)
print(Dog.__name__)
print(Dog.__module__)
print(Dog.__bases__)
"""
This is about dog class.
Dog
__main__
(<class 'object'>,)
"""
import class
"""
from file_name import class_name_1,class_name_2,...,class_name_n
"""
from car import Car, ElectricCar