5

it2022-05-05  65

1. 实例属性和类属性

       (1) 实例属性在构造函数__init__中定义,定义时以self作为前缀,只能通过实例名访问

       (2) 类属性在类中方法之外单独定义,还可以在程序中通过类名增加,建议通过类名直接访问。

class Product: ##建议首字母大写 price = 100 ##类属性 def __init__(self,c): self.color = c ##实例属性 ##主程序 Product1 = Product("red") Product2 = Product("yellow") Product.price = 120 ##修改类属性值 Product.name = "shoes" ##增加类属性 Product1.color = "black" ##修改实例属性

       (3) 私有属性以__开头,否则是公有属性。私有属性在类外不能直接访问。而是通过特殊方式访问私有属性:

class Food: def __init__(self): self.__color = 'red' ##私有属性定义格式 self.price = 0 ##主程序 >>>apple = Food() >>>apple.(_)Food__color = "blue" ##私有属性修改格式 >>>print(apple._Food__color) ##私有属性访问格式 blue

2. 类的方法

class Fruit: price = 0 ##类属性 def __init__(self): self.__color = 'red' ##私有属性 def __outputColor(self): ##私有方法 print(self.__color) def output(self): ##公有方法 self.__outputColor() @staticmethod ##静态方法 def getprice(): return Fruit.frice @classmethod ##类方法 def fget(cls): print(cls)

3. 构造函数和析构函数

def __init__(self,first = '',last = '',id = 0): self.firstname = first self.lastname = last self.idint = id def __del__(self): print("self was dead")

4. 常用的运算符重载

方法重载调用__add__+x+y__or__|x|y__repr__打印repr(x)__str__转换str(x)__call__函数调用x(*args,**key)__getattr__点号运算x.undefine__setattr__属性赋值x.any=value__delattr__属性删除del x.any__getattribute__属性获取x.any__getitem__[]x[key]__setitem__索引赋值x[key]=value__delitem__索引删除del x[key]__len__长度len(x)__bool__布尔测试bool(x)__lt__,__gt__小于,大于__le__,__ge__小于等于,大于等于__eq__,__ne__等于,不等于__contain__initem in x__iter__,__next__迭代I=iter(x),next(x)

5. 继承

        与C++继承实现类似

class sub(super): def __init__(self):

转载于:https://www.cnblogs.com/machine-lyc/p/10636582.html

相关资源:real_python_oop-源码

最新回复(0)