类与对象

mac2026-01-05  8

什么是类?

class Person(): def __init__(self,color,height,sex): self.color=color self.height=height self.sex=sex def show_color(self): print('My color is ',self.color) def show_height(self): print('My height is ',self.height,' cm') def show_sex(self): print('My sex is ',self.sex) >>> p=Person('Yellow',180,'man') >>> p.show_color() My color is Yellow

其中Person就是类对象,而p为Person的实例对象。 其中color,height,sex为类对象的类属性 而show_color,show_height,show_sex则为实例方法 此外color,height,sex均属于公有类属性 类属性中除了共有类属性,还有私有类属性 私有类属性在名字面前加上_,则外部无法访问到它 有人提到了实例属性,下面链接作为参考 实例属性与类属性的关系 还有人说到了类方法和静态方法 类方法,实例方法和静态方法的对比 继承和多态

>>> class Yellow_Person(Person): def __init__(self,height,sex): self.height=height self.sex=sex def show_color(self): print('My color is Yellow') >>> a=Yellow_Person(170,'woman') >>> a.show_color() My color is Yellow >>> a.show_height() My height is 170 cm

这就是我继承的刚刚的Person类 我定义了一个YellowPerson的类继承了Person类 它也具备身高,性别,但肤色统一为黄色 其余的都继承,但有些地方要重写 init重写的,show_color的实例方法也进行了重写

def Classson(Class1,Class2,Class3):

可以进行继承多个,则体现出了多态性

最新回复(0)