标签:参数 init sel 实例化 object 绑定 %s code lin
类有两种属性:数据属性和函数属性
class LuffyStudent:
school = 'Luffy'
def __init__(self, name, sex, age):
self.name = name
self.sex = sex
self.age = age
def learn(self, class_name):
print('%s 正在学习 %s' % (self.name, class_name))
def eat(self):
print('吃东西')
def sleep(self):
print('睡觉')
s1 = LuffyStudent('王青', '女', 18)
s2 = LuffyStudent('江子牙', '男', 21)
# 类中的数据属性是类属性,是所有对象共有的,在内存中只有一份
print(LuffyStudent.school,id(LuffyStudent.school)) # Luffy 2243589824616
print(s1.school,id(s1.school)) # Luffy 2243589824616
print(s2.school,id(s2.school)) # Luffy 2243589824616
# 类中的函数属性:是绑定给对象,绑定到不同对象
print(LuffyStudent,)
print(s1.learn) # bound method LuffyStudent.learn of <__main__.LuffyStudent object at 0x000001CC059EED30
print(s2.learn) # bound method LuffyStudent.learn of <__main__.LuffyStudent object at 0x000001CC059EED68
定义类并实例化三个对象
class LuffyStudent:
school = 'Luffy'
def __init__(self, name, sex, age):
self.name = name
self.sex = sex
self.age = age
def learn(self, class_name):
print('%s 正在学习 %s' % (self.name, class_name))
def eat(self):
print('吃东西')
def sleep(self):
print('睡觉')
s1 = LuffyStudent('王青', '女', 18)
s2 = LuffyStudent('江子牙', '男', 21)
s3 = LuffyStudent('江薏米', '女', 0)
# 类调用函数
LuffyStudent.learn(s1,'Java') # 王 青 正在学习 Java
LuffyStudent.learn(s2,'Linux') # 江子牙 正在学习 Linux
# 对象调用函数:自动把对象传给self
s3.learn('C++') # 江薏米 正在学习 C++
s1.learn('Go') # 王 青 正在学习 Go
标签:参数 init sel 实例化 object 绑定 %s code lin
原文地址:https://www.cnblogs.com/xjmlove/p/10319098.html