直接修改父类属性
class Father:age = 40class Son(Father):def modify_age(self):Father.age = 50f = Father()s = Son()print("Father's age:", f.age) 输出:Father's age: 40s.modify_age()print("Father's age after modification:", f.age) 输出:Father's age after modification: 50
使用`super()`函数调用父类方法
class Parent:kids = 2def family_number(self, kids=None):if kids is None:kids = self.kidsreturn kids * 2class Child(Parent):kids = 3c = Child()print(c.family_number()) 输出:6,因为子类覆盖了父类的属性,所以使用子类的属性值
重写父类方法
class Conn(object):def __init__(self, host, passwd, port):self.host = hostself.passwd = passwdself.port = portclass ConnMySql(Conn):def __init__(self, host, passwd, port, username, db, charset='utf8'):super().__init__(host, passwd, port)self.username = usernameself.db = dbself.charset = charsetclass ConnRedis(Conn):def conn(self, host, passwd, port):super().conn(host, passwd, port)这里可以添加额外的连接逻辑
在重写父类方法时,使用`super()`函数可以确保父类的方法被正确调用,同时可以在子类中添加额外的逻辑。
以上是修改父类属性的几种常见方式,您可以根据具体需求选择合适的方法

