什么是类?
分类 class , 抽象个概念,一类事务的总称
对象?
类的实例 ,对象是一个实例
定义类: 类命名的规范:首字母要大写,下划线 user_name 或者 大驼峰法 UserName
【面向对象的封装:将属性和方法封装到一个类多个类,需要使用的时候,调用这些属性和方法】
方法一:
【get,set方法】
class User(object):
def __init__(self, name, age, gender):
self.__name = name
self.__age = age
self.__gender = gender
def __str__(self):
return "name=" + self.__name +"age=" + str(self.__age) +"gender=" + self.__gender
def get_name(self):
return self.__name
def set_name(self, username):
self.__name = username
def get_age(self):
return self.__age
def set_age(self, age):
self.__age = age
def get_gender(self):
return self.__gender
def set_gender(self, gender):
self.__gender = gender
if __name__ == '__main__':
u = User("张三", 18, "男")
print(u.get_name())
u.name = "lisi"#更改姓名
print(u.name)
方法二:
【property()】
class User(object):
def __init__(self, name, age, gender):
self.__name = name
self.__age = age
self.__gender = gender
def __str__(self):
return "name=" + self.__name +"age=" + str(self.__age) +"gender=" + self.__gender
def get_name(self):
return self.__name
def set_name(self, username):
self.__name = username
def get_age(self):
return self.__age
def set_age(self, age):
self.__age = age
def get_gender(self):
return self.__gender
def set_gender(self, gender):
self.__gender = gender
name = property(get_name, set_name)
age = property(get_age, set_age)
gender = property(get_gender, set_gender)
if __name__ == '__main__':
u = User("张三", 18, "男")
print(u)
u.name = "lisi"#更改姓名
print(u.name)
方法三:
【装饰器 @property】
class User(object):
def __init__(self, name, age, gender, tel):
self.__name = name
self.__age = age
self.__gender = gender
self.__tel = tel
def __str__(self): return "name=" + self.__name
@property
def name(self):
return self.__name
def age(self):
return self.__age
def gender(self):
return self.__gender
@name.setter
def name(self, username):
self.__name = username
def age(self, age):
self.__name = age
def gender(self, gender):
self.__name = gender
if __name__ == '__main__':
u = User("张三", 18, "男", "110")
print(u.name)
u.name = "李四"
print(u)
注意:重写的时候方法名、参数以及参数的个数必须保持一致
class User(object):
def __init__(self):
self.money=100000
def tell(self):
print("好")
def animal(self):
print("猫在跑")
class User1(User):
def animal(self):
print("狗在跑")
super().animal()
if __name__=='__main__':
u=User1()
print(u.money)
print(u.tell())
print(u.animal())
Python中多态的作用
Python中多态的特点