Python 类
定义一个类
方法**init()**
每当创建新实例时,Python会自动运行该方法。在这个方法名称中,开头和末尾各有两个下划线,这是一种约定,旨在避免Python默认方法与普通方法发生名称冲突。
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(self):
"""小狗打滚"""
print(self.name.title()+" is now rolling")
属性和方法的调用
dog=Dog("bobby",4)
print("The dog's name is "+dog.name.title()+",age is "+str(dog.age)+".")
dog.sit()
dog.roll()
程序输出:
The dog's name is Bobby,age is 4.
Bobby is now sitting.
Bobbyis now rolling
修改属性的值
可以用三种不同的方式修改属性的值:直接通过实例进行修改;通过方法进行设置;通过方法进行递增。
1.直接通过实例修改
class Animal():
def __init__(self,name,age):
self.name=name
self.age=age
self.home='china'
def get_info(self):
info=self.name+" "+str(self.age)+" "+self.home
return info
bird=Animal('lucy',3)
print(bird.get_info())
bird.age=bird.age+1
print(bird.get_info())
程序输出:
lucy 3 china
lucy 4 china
2.通过方法修改属性值
class Animal():
def __init__(self,name,age):
self.name=name
self.age=age
self.home='china'
def set_name(self,name):
self.name=name
def get_info(self):
info=self.name+" "+str(self.age)+" "+self.home
return info
bird=Animal('lucy',3)
print(bird.get_info())
bird.set_name('qiu')
bird.set_age(6)
print(bird.get_info())
程序输出:
lucy 3 china
qiu 6 china
3.通过方法对属性的值进行递增
class Animal():
def __init__(self,name,age):
self.name=name
self.age=age
self.home='china'
def update_age(self):
self.age+=1
def get_info(self):
info=self.name+" "+str(self.age)+" "+self.home
return info
bird=Animal('lucy',3)
print(bird.get_info())
bird.update_age()
bird.update_age()
print(bird.get_info())
程序输出:
lucy 3 china
lucy 5 china
继承
一个类继承另一个类时,它将自动获得另一个类的所有属性和方法;原有的类称为父类,而新类称为子类。子类继承父类的所有属性和方法,同时还可以定义自己的属性和方法。
创建子类时,子类必须包含在当前文件中,且位于子类前面。
定义子类时,必须在括号内指定父类的名称。
class Animal():
"""创建一个动物类"""
def __init__(self,name,age):
self.name=name
self.age=age
def set_name(self,name):
self.name=name
def set_age(self,age):
self.age=age
def eat(self):
print(self.name.title()+" can eat")
def sleep(self):
print(self.name.title()+"can sleep")
def get_info(self):
info=self.name+" "+str(self.age)
return info
class Cat(Animal):
"""创建Cat继承Animal"""
def __init__(self,name,age):
super().__init__(name,age)
self.home='China'
def get_info(self):
info=self.name+" "+str(self.age)+" "+self.home
return info
cat=Cat("kitty",2)
print(cat.get_info())
cat.eat()
cat.sleep()
程序输出:
kitty 2 China
Kitty can eat
Kittycan sleep
一开始应让代码结构尽可能简单。先尽可能在一个文件中完成所有的工作,确定一切都能正常运行后,再将类移到独立的模块中。
类编码风格
1.类名应采用驼峰命名法,即将类名中的每个单词首字母都大写,而不使用下划线。
2.实例名和模块名都采用小写格式,并在单词间加上下划线。
3.对于每个类,都应紧跟在类定义后面包含一个文档字符串。每个模块也都应该包含一个文档字符串,对其中的类可用于做什么进行描述。
4.可使用空行来组织代码,但不要滥用。在类中,可使用一个空行来分割方法;而在模块中,可使用两个空行来分隔类。
5.如果需要同时导入标准库中的模块和你编写的函数时,先编写导入标准库模块的imort语句,再添加一个空行,然后编写你自己编写的模块的import语句。