码迷,mamicode.com
首页 > 编程语言 > 详细

python3 面向对象

时间:2019-12-05 13:10:50      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:属性   pre   http   类中访问   sel   color   col   object   class   

"""
语法:
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车会跑

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

 

 

python3 面向对象

标签:属性   pre   http   类中访问   sel   color   col   object   class   

原文地址:https://www.cnblogs.com/lilyxiaoyy/p/11988523.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!