# 1.类的属性
class cat:
name = '布偶'
age = 9
p1 = cat # 这是一个cat类
print(p1)
print(p1.name)
p2 = cat() # 这是一个cat对象
print(p2)
print(p1.name)
p3 = cat
p3.name = '毛线' # 属性会优先找对象,对象没有才会去类找
print(p2.name)
print(p2.__dict__) # {} __dict__获取对象的字典信息
print(p2.__class__) # 查看类型
print(cat.__dict__)
# 2.初始化属性
class Teacher:
school = "oldboy"
# def init(obj, name, age):
# obj.name = name
# obj.age = age
def __init__(self, name, age):
print(self)
self.name = name
self.age = age
t1 = Teacher("jack", 18)
print(t1.name)
print(t1)
# 3.行为定制
class Student:
school = "oldgirl"
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
# def study(self):
# print(self)
def say_hi(self):
# print(self)
print("hello i am a student! my name:%s" % self.name)
def a(self):
pickle
stu1 = Student("jack", 20, "male") # 这是一个对象
stu2 = Student("rose", 18, "female")
# stu1.say_hi()
# stu2.say_hi()
# print(stu1)
# stu2.say_hi() # 对象调用函数
# Student.say_hi(stu1) # 类调用函数
print(type(Student.say_hi))
print(type(stu1.say_hi))
# 4.类绑定方法
class OldBoyStudent:
school = "oldboy"
def __init__(self,name):
self.name = name
@classmethod # 类绑定方法
def show_school(cls):
# print(self.school)
print(cls)
@staticmethod # 当作普通函数
def print_hello():
print("hello world")
转载于:https://www.cnblogs.com/night-rain/p/11241678.html