Class constructor and init method and self address problem

The methods defined in functions and classes are all def, but methods must have self.
Init is standardized to ensure that every object created has this attribute.
Self is constantly changing

// #函数 和类里面定义的方法 都是def  不过方法要有self
def func(names):
    for name in names:
        print(name)

name_list=['sa','ga','bb']
func(name_list)

class Phone:
    #魔术方法之一  称为魔术方法  __名字__()
    def __init__(self):  #init 初始化初始的  只要你创建一个对象引用Phone 就会调用init
        print('-----init',self)
        self.brand='huawei'    #init是标准化 保证每一个创建的对象都有这个属性
        self.price=4999


    def call(self):   #self是不断发生改变的
        print('call-------------')
        print('价格',self.price)   #不能保证每个self都有price

print(Phone())
p=Phone()
print(p)
p.price=10000  #如果外部没有定义price 那就继承init中定义的price值 4999
p.call()  #p.call()  p是类的对象 p在解释器就是一个内存地址  哪个对象调用call 就把call放进这个地址中
           #系统自动把p传入self  所以call中不用写入参数
print(p.brand)


print('---------------------以下为p1新对象--------------')
p1=Phone()  #p1又创建一个新内存地址 p1调用call时 把call存入p1地址中

p1.call()

运行结果如下:
sa
ga
bb
-----init <__main__.Phone object at 0x000002A6EE6C0E10>
<__main__.Phone object at 0x000002A6EE6C0E10>
-----init <__main__.Phone object at 0x000002A6EE6C0E10>
<__main__.Phone object at 0x000002A6EE6C0E10>
call-------------
价格 10000
huawei
---------------------以下为p1新对象--------------
-----init <__main__.Phone object at 0x000002A6EE6C0F28>
call-------------
价格 4999
下面展示一些 `内联代码片`

// The following shows the steps of calling the self memory address
p=Phone()
1. Find a space and write the Phone class
2. Create an object p, apply for a memory address
3 that is exactly the same as Phone , and then go to Phone to find if __init__ , If any, it will enter the init method to execute the actions inside. The
simple code is as follows

// class func:
    name='555'
    def eat(self):
        print("嘿嘿")

print(func())
p1=func()
print(p1)
print('----------------')
print(func().eat())
print(p1.eat())
p2=func()
print(p2)

结果为

<__main__.func object at 0x000001E60F5A97B8>
<__main__.func object at 0x000001E60F5A97B8>
----------------
嘿嘿
None
嘿嘿
None
<__main__.func object at 0x000001E60F5A9748>



Insert picture description here
Insert picture description here

Exercise 2

//class Person:
    name=('张三')
    def __init__(self,name,age):
        self.name=name  #当init中定义了self.name后  原类中的name将被self.name覆盖
        self.age=age
    def eat(self,food):
        print('{}正在吃->{}'.format(self.name,food))
    def run(self):
        print('{},今年{}岁,正在跑步中'.format(self.name,self.age))

p1=Person('李思',15)    #调用类的同时进行传参 ,init中定义了几个参数 你就必须传几个参数
p1.eat('烤肉')   #向类内部的方法传参
p1.age=25  #即使上边传了参 但在此时再次定义 就会覆盖
p1.run()



结果如下
李思正在吃->烤肉
李思,今年25岁,正在跑步中



// Exercise 2 code memory relationshipInsert picture description here

Guess you like

Origin blog.csdn.net/weixin_43516990/article/details/108679431