python3 初识面向对象

"""
语法:
class 类名
图纸就是一个类,根据图纸造出来的每辆车就是一个对象。

1、属性:能够描述一个对象的变量(变量)
2、动作:能够描述一个对象能执行的动作(函数)

在类中访问属性:self.属性
在类中访问动作:self.动作
""" class Car: def __init__(self, color): # self就是对象 self.color = color # 属性 def run(self): # 动作 print("我的车会跑") # 创建对象 init 初始化 出厂设置 c1 = Car("red") # 类名() => 实际上默认执行的是__init__函数 c2 = Car("white")

self到底是个什么鬼?

class Car:
    def __init__(self, color):  # self就是对象
        print(self)  # self到底是个什么鬼
        self.color = color  # 属性

    def run(self):  # 动作
        print("我的车会跑")


c1 = Car("red")  
print(c1)

执行结果:

<__main__.Car object at 0x000000000228CEB8>
<__main__.Car object at 0x000000000228CEB8>

 结论:self就是对象

不同对象调用同一方法,会有什么样的效果呐?

class Car:
    def __init__(self, color):  # self就是对象
        print(self)  # self到底是个什么鬼
        self.color = color  # 属性

    def run(self):  # 动作
        print(f"我的{self.color}车会跑")


c1 = Car("red")  
c2 = Car("white")
c1.run()
c2.run()

执行结果:

<__main__.Car object at 0x00000000029997F0>
<__main__.Car object at 0x0000000002999828>
我的red车会跑
我的white车会跑

结论:不同对象调用同一属性或方法,调用的是对象自己的属性和方法。

猜你喜欢

转载自www.cnblogs.com/lilyxiaoyy/p/11988523.html