# 类变量
class Student:
student_count = 50 # 类变量
s1 = Student()
print(getattr(Student, "student_count"))
print(s1.student_count)
setattr(Student, "student_count", 70) # 设置类变量
getattr(Student, "student_name", "jack")
# 调用类变量,如果类中没有定义调用的这个变量,可以设置缺省值返回,程序不会报错,如果类名.类变量直接调用程序就会报错
print(Student.student_count) # 调用类变量
# 实例变量和函数
class Animal:
def __init__(self, name: str):
self.name = name
def animal_call(self):
print(f"{self.name}一直在叫!!")
a1 = Animal("cat")
a1.animal_call()
a2 = Animal("小狗")
a2.animal_call()
# 私有属性与函数
class Car:
def __init__(self,brand: str,color: str):
self._brand = brand # 一个下划线是被保护的属性
self.__color = color # 两个下划线是私有属性,从外部调用程序会报错
def __run(self):
print(f"{self.__color}的{self._brand}汽车在路上跑")
c1 = Car("大众","红色")
print(c1._brand)
print(c1._Car__color) # 私有属性用_类名__私有属性名才可直接调用,但是不建议用
c2 = Car("宾利","白色")
c2._Car__run() # 私有方法与私有属性用法相同
python 类变量,实例变量,私有属性及函数
最新推荐文章于 2024-07-12 16:16:27 发布