class Employee:
up = 0.1
def __init__(self,name ,salary):
#构造器 __init__
self.username = name #实例变量
self.salary = salary1
def up_salary(self): #self 表示的就是实例
self.salary = self.salary * (1 + self.up)
if __name__ == '__main__':
# Employee.up = 0.2 #修改类变量,它会影响整个的一个实例
p1 = Employee('张三',10000)
p1.up = 0.2
p1.up_salary()
print('张三',p1.salary)
p2 = Employee('李四',8000)1
p2.up_salary()
print('李四',p2.salary)
通过继承让类拥有更多的属性
class Animal:
def __init__(self,name ,legs):
self.name = name
self.legs = legs
def info(self):
print(f'name: {self.name}, legs: {self.legs}')
class Dog(Animal):
def info(self): #info(self,other)#写入形参后,父类中的info方法覆盖
print(f'name: {self.name}, legs: {self.legs}')
class Cat(Animal):
def walk(self):
print(f'{self.name}用{self.legs}条腿走路')
if __name__ == '__main__':
d = Dog('旺财',4)
d.info() #当父类被覆盖后写入实参来得出结果
c = Cat('凯蒂丝',4)
c.walk()
class Person:
def __init__(self,name):
self.__name = name #当设置为私有的时候在类的外部是访问不到的
@property
def name(self): #在类的内部访问后用return返回,就可以调用这个方法把私有打印出来
return self.__name
#@name.setter #用来更新私有变量,一般是于@property一同使用
#def name(self,value):
#self.__name = value
# --------