对象的属性不能继承。
方法可以调用没有的参数或方法,但运行时会报错。
方法可以调用没有的参数或方法,但运行时会报错。
@property@XXX.setter标记的方法可以当作属性来用。
class Animal(object):
def __init__(self):
self.age="yi"
def run(self):
print(self.name,"is running")
class Peple(object):
def run(self):
print("peple is running")
def run2(xx):
xx.run()
class Dog(Animal):
__name=""
__slots__ = ('age') # 用tuple定义允许绑定的属性名称
def __init__(self):
self.a , self.b = 0 , 1
def __str__(self):
return 'Dog (name: %s)' % self.name # __name一样
def __iter__(self):
return self
def __next__(self):
self.a ,self.b = self.b , self.a+self.b
if self.a>100:
raise StopIteration()
return self.a
def __getitem__(self,n):
d = Dog()
for x in range(n):
next(d)
return d.a
@property
def name(self):
return self.__name
@name.setter
def set_name(self,value):
if len(value)>3:
raise ValueError("长度不能大于三")
self.__name = value
@property
def english_name(self):
return self.__name+"zhi"
peple = Peple()
dog = Dog()
run2(peple)
run2(dog)#证明多态性,只要有run方法即可
print("origin name:",dog.name)
dog.set_name="liu"
print("after set name:",dog.name)
dog.run()
print(dog)
print("english name:",dog.english_name)
for n in dog:
print(n)
print("getitem=====5n=",dog[5])
dog.set_name="我是五大锤"
print("after set name:",dog.name)
创建类
def fn(self, name='world'): # 先定义函数
print('Hello, %s.' % name)
Hello = type('Hello', (object,), dict(hello=fn)) # 创建Hello class
h = Hello()
h.hello()