class Student(object): 属性 方法
实例化:bart = Student() 构造方法:init
class Student(object): def __init__(self, name, score): self.name = name self.score = score私有变量:__开头
class Student(object): def __init__(self, name, score): self.__name = name self.__score = score def get_name(self): return self.__name def get_score(self): return self.__score def set_score(self, score): self.__score = score类的继承:
class Animal(object): def run(self): print('Animal is running...') class Dog(Animal): pass class Cat(Animal): pass紧接着,可以测试该对象的属性:
>>> hasattr(obj, 'x') # 有属性'x'吗? True >>> hasattr(obj, 'y') # 有属性'y'吗? False >>> setattr(obj, 'y', 19) # 设置一个属性'y' >>> getattr(obj, 'y') # 获取属性'y' 19 >>> getattr(obj, 'z', 404) # 获取属性'z',如果不存在,返回默认值404 404 >>> hasattr(obj, 'power') # 有属性'power'吗? True >>> fn = getattr(obj, 'power') # 获取属性'power'并赋值到变量fn >>> fn >>> fn() # 调用fn()与调用obj.power()是一样的 slots 只允许对Student实例添加name和age属性。 class Student(object): __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称 s = Student() s.score = 99 # 绑定属性'score'由于’score’没有被放到__slots__中,所以不能绑定score属性,试图绑定score将得到AttributeError的错误。
使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的.
str 我们先定义一个Student类,打印一个实例: class Student(object): def __init__(self, name): self.name = name def __str__(self): return 'name: %s' % self.name print(Student('Michael')) iter()和__next__() 返回一个迭代对象,然后,Python的for循环就会不断调用该迭代对象的__next__()方法拿到循环的下一个值,直到遇到StopIteration错误时退出循环。写一个迭代Fib类,可以作用于for循环:
class Fib(object): def __init__(self): self.a, self.b = 0, 1 # 初始化两个计数器a,b def __iter__(self): return self # 实例本身就是迭代对象,故返回自己 def __next__(self): self.a, self.b = self.b, self.a + self.b # 计算下一个值 if self.a > 100000: # 退出循环的条件 raise StopIteration() return self.a # 返回下一个值现在,试试把Fib实例作用于for循环:
>>> for n in Fib(): ... print(n) ... 1 1 2 3 5 ... 46368 75025 getitem 取第5个元素: class Fib(object): def __getitem__(self, n): a, b = 1, 1 for x in range(n): a, b = b, a + b return a >>> f[0] 1 >>> f[1] 110 call
任何类,只需要定义一个__call__()方法,就可以直接对实例进行调用。请看示例:
class Student(object): def __init__(self, name): self.name = name def __call__(self): print('My name is %s.' % self.name)调用方式如下:
>>> s = Student('Michael') >>> s()使用时: s.score = 60 2. @classmethod 3. @staticmethod静态方法,只能类使用。
