2024.11.25
一、类的定义

二、类与实例的关系



# 定义一个猫类,age, name, color 是属性,或者称为成员变量
class Cat:age=Nonename=Nonecolor=Nonecat1=Cat()
#通过对象名.属性名,可以给各个属性赋值
cat1.name="小白"
cat2,age=2
cat3.color="白色"print(f"cat1的信息:name:{cat1.name} age:{cat1.age} color:{cat1.color}")
三、类与对象的区别和联系

四、属性/成员变量


五、类的定义和使用

六、对象的传递机制




b这个会报错
七、对象的布尔值

print("---下面对象的布尔值为False---")
print(bool(False))
print(bool(0))
print(bool(None))
print(bool(""))
print(bool([]))
print(bool(()))
print(bool({}))
print(bool(set()))# 因为所有对象都有一个布尔值,所有有些代码直接使用对象的布尔值做判断
content = "hello"
if content:print(f"hi {content}")
else:print("空字符串")lst = [1, 2]
if lst:print(f"lst {lst}")
else:print("空列表")
八、成员方法


class Person:def hi(self):print("hi,python")def calo1(self):result=0for i in range(1,1001):result+=iprint(f"result={result}")def cal20(self):result2=0for i in range(1,n+1):result2+=iprint(f"result={result2}")def get_num(self,n1,n2):return n1+n2
p=Person()
p.hi()
p.cal01(10)
p.get_num(10,20)
# 函数
def hi():print("hi, python")# 定义类
class Person:age = Nonename = Nonedef ok(self):pass# 创建对象 p、p2
p = Person()
p2 = Person()# 动态地给p对象添加方法m1,注意:只是针对p对象添加方法
# m1 是你新增加的方法的名称,由程序员指定名称
# 即 m1方法和函数hi关联起来,当调用m1方法时,会执行hi函数
p.m1 = hi# 调用m1(即hi)
p.m1()print(type(p.m1), type(hi)) # <class 'function'> <class 'function'>
print(type(p.ok)) # <class 'method'># 因为没有动态的给p2 添加方法,会报错
p2.m1() # AttributeError: 'Person' object has no attribute 'm1'