标签:python elf 需要 而不是 cab main 多实例 attribute name
类名首字母应该大写
class FirstClass:
def setdate(self,value): # 类中的方法使用时会隐式传入类本身和值,所以需要一个self来接收本身
self.data = value # 新建类的一个变量并且赋值
def display(self):
print(self.data) # 调用类的变量,如果直接用data会会报错
class Second(FirstClass): # 重写类
def display(self):
print("Current value is %s"%self.data)
z = Second()
z.setdate(42)
z.display(42)
class FistClass:
def setdate(self,value):
self.data = value
def display(self):
print(self.data)
class Second(FistClass):
def display(self):
print("Current value is %s"%self.data)
class ThirdClass(Second):
def __init__(self,value): # __init__作用为为类进行初始化
self.data = value
def __add__(self, other):
return ThirdClass(self.data+other)
def __str__(self): # 作用为输出类的描述性内容,当print时输出此内容
return '[ThirdClass:%s]'% self.data
def mul(self,other):
self.data *= other
a = ThirdClass('abc')
a.display()
print(a)
b = a + 'xyz'
b.display()
print(b)
a.mul(3)
print(a)
# Current value is abc
# [ThirdClass:abc]
# Current value is abcxyz
# [ThirdClass:abcxyz]
# [ThirdClass:abcabcabc]
class Person:
def __init__(self,name,job = None,pay = 0):
self.name = name
self.job = job
self.pay = pay
def lastname(self):
return self.name.split()[-1]
def giveRaise(self,percent): # 涨工资方法
self.pay = int(self.pay * (1 + percent))
def __str__(self): # 每当打印类的时候调用这个方法
return "[Person:%s,%s]"%(self.name,self.pay)
class Manger(Person): # 一个管理者类,每次涨薪水固定10%加提成
def __init__(self,name,pay):
Person.__init__(self,name,'mgr',pay)
def giveRaise(self,percent,bonus = .10):
Person.giveRaise(self,percent+bonus) # 直接调用原始代码逻辑,方便后期代码维护
if __name__ == "__main__" :
bob = Person('Bob Smith')
sue = Person('Sue Jones', job='dev',pay=100000)
print(bob)
print(sue)
print(bob.lastname(),sue.lastname())
sue.giveRaise(.10)
print(sue)
tom = Manger('Tom Jones',50000)
tom.giveRaise(.10)
print(tom.lastname())
print(tom)
print('-----all three -----')
for object in (bob,sue,tom): # object仅仅是一个变量名,迭代对对象进行操作
object.giveRaise(.1)
print(object)
标签:python elf 需要 而不是 cab main 多实例 attribute name
原文地址:https://www.cnblogs.com/yingyingdeyueer/p/11852957.html