python(9)类和对象及常用魔法方法

mac2026-09-27  13

python(9)类和对象

类的基本使用

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

类常用函数:

type()函数: >>> type(123) <class 'int'> >>> type('str') <class 'str'> >>> type(abs) <class 'builtin_function_or_method'> >>> type(a) <class '__main__.Animal'> isinstance() >>> isinstance(h, Husky) True dir() 获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list >>> dir('ABC') getattr()、setattr()以及hasattr() class MyObject(object): def __init__(self): self.x = 9 def power(self): return self.x * self.x obj = MyObject()

紧接着,可以测试该对象的属性:

>>> 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] 1

10 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()

装饰器

@property Python内置的@property装饰器就是负责把一个方法变成属性调用的: class Student(object): #把一个getter方法变成属性 @property def score(self): return self._score #把一个setter方法变成属性赋值 @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError('score must between 0 ~ 100!') self._score = value

使用时: s.score = 60 2. @classmethod 3. @staticmethod静态方法,只能类使用。

最新回复(0)