Discuss / Python / 类属性与实例属性辨析

类属性与实例属性辨析

Topic source
class Car:
    _color = ""
    def description(self,name):
        self.name=name
        description_string = "This is a %s car %s." % (self._color ,self.name)
        return description_string
car1 = Car()
car1._color = "blue"  #实例可以重写类属性
print(car1.description('11')) #This is a blue car 11.
print(hasattr(Car,'name')) #False
print(hasattr(Car,'_color')) #True
print(hasattr(car1,'name')) #True
print(hasattr(car1,'_color')) #True
print(Car.name) #Error. 类无法直接访问实例属性
print(car1.name) #11

类属性:写在类内部,方法外部的属性 实例属性:写在类的方法内部的属性


  • 1

Reply