1. 程式人生 > >面向物件 3 屬性查詢與繫結方法&python中一切皆為物件

面向物件 3 屬性查詢與繫結方法&python中一切皆為物件

屬性查詢與繫結方法



x='全域性'
class LuffyStudent:
    school = 'luffycity'

    #  stu1,'王二丫','女',18
    def __init__(self,name,sex,age):
        self.Name = name
        self.Sex = sex
        self.Age = age

        #stu1.Name='王二丫'
        # stu1.Sex = '女'
        #stu1.Age = 18
    def learn(self,x):
        print('%s is learning %s'%(self.Name,x))

    def eat(self):
        print('%s is eating'%self.Name)


#後產生物件

stu1 = LuffyStudent('王二丫','女',18)
stu2 = LuffyStudent('李三','男',38)
stu3 = LuffyStudent('張四','男',48)
# print(stu1.__dict__)
# print(stu2.__dict__)
# print(stu3.__dict__)

#類中的資料屬性,是所有物件共有的
# print(LuffyStudent.school,id(LuffyStudent.school))
#
# print(stu1.school,id(stu1.school))
# print(stu2.school,id(stu1.school))
# print(stu3.school,id(stu1.school))


#類中的函式屬性:是繫結給物件的,繫結到不同的物件是不同的繫結方法,物件呼叫繫結方法是,會把物件本身當作第一個傳入,穿個self

# print(LuffyStudent.learn)
# LuffyStudent.learn(stu1)
# LuffyStudent.learn(stu2)
# LuffyStudent.learn(stu3)

# print(stu1.learn)
# stu1.learn(1)  #learn(stu1)
# print(stu2.learn)
# print(stu3.learn)
#
# stu2.learn(2)
# stu3.learn(3)

stu1.x='from stu1'
# LuffyStudent.x='from luffycity class'

print(stu1.__dict__)
print(stu1.x)

補充說明 1、站的角度不同,定義出的類截然不同的 2、現實中的類並不完全等於程式中的類,比如現實中的公司類,在程式中有時需要拆分成部門類,業務類等 3、有時為了程式設計需求,程式中也可能會定義現實中完全不存在的類,比如策略類,現實中不存在,但是在程式中是很常見的類 python中一切皆為物件

python中一切皆為物件,並且在python3裡統一類類與型別的概念


# print(type([1,2]))

# print(list)

class LuffyStudent:
    school = 'luffycity'

    #  stu1,'王二丫','女',18
    def __init__(self,name,sex,age):
        self.Name = name
        self.Sex = sex
        self.Age = age

        #stu1.Name='王二丫'
        # stu1.Sex = '女'
        #stu1.Age = 18
    def learn(self,x):
        print('%s is learning %s'%(self.Name,x))

    def eat(self):
        print('%s is eating'%self.Name)

# print(LuffyStudent)

l1=[1,2,3]

l2=[]
list.append(l1,4)
print(l1)