Python类方法访问属性

Python类方法访问属性教程

Python 中的 实例方法 可以访问类中的 类属性实例属性,实例方法访问类属性或者实例属性使用 “self.” 的形式。

Python 中的 类方法 可以访问类中的类属性但不可以访问实例属性,类方法访问类属性也是使用 “cls.” 的形式。

Python实例方法访问属性详解

语法

class People: money = 10000 def __init__(self, name): self.name = name def func_name(self): print("Name =", self.name, "Money =", self.money) p = People("Haicoder") p.func_name()

说明

我们定义了一个 Person 类,Person 类中有一个 构造函数 和一个实例方法 func_name,构造函数接受一个 name 参数

接着,我们在实例方法 func_name 中使用 self 访问了类的实例属性 name 和类属性 money。

案例

实例方法访问类属性

实例方法使用 self 访问类属性

print("嗨客网(www.haicoder.net)") class Student: score = "Python" def __init__(self, name, age): self.name = name self.age = age def info(self): print("I am", self.name, "and i am", self.age, "years old", "study", self.score) stu = Student("William", 18) stu.info()

程序运行后,控制台输出如下:

38_python类方法访问属性.png

我们创建了一个类 Student,接着,为该类添加了一个类属性 score,一个构造函数,接受额外的 name 属性和 age 属性,一个 info 实例方法。

我们在实例方法 info 里,使用 self 访问了类属性 score 和实例方法 name 和 age。最后,我们发现,在 info 函数里面,我们成功的获取了类属性和实例属性的值。

类方法访问类属性

类方法使用 self 访问类属性

print("嗨客网(www.haicoder.net)") class Student: score = "Python" def __init__(self, name, age): self.name = name self.age = age @classmethod def info(cls): print("I am study", cls.score) stu = Student("William", 18) stu.info()

程序运行后,控制台输出如下:

39_python类方法访问属性.png

我们创建了一个类 Student,接着,为该类添加了一个类属性 score,一个构造函数和一个 info 类方法。在类方法 info 里,我们使用 cls 访问了类属性。

类方法不能访问实例属性

类方法不能访问实例属性

print("嗨客网(www.haicoder.net)") class Student: score = "Python" def __init__(self, name): self.name = name @classmethod def info(cls): print("I am", cls.name, "study", cls.score) stu = Student("William") stu.info()

程序运行后,控制台输出如下:

40_python类方法访问属性.png

我们在类方法 info 里访问了实例属性 name,程序报错,即类方法不可以访问类属性。

Python类方法访问属性总结

Python 中的实例方法可以访问类中的类属性和实例属性,实例方法访问类属性或者实例属性使用 “self.” 的形式。

Python 中的类方法可以访问类中的类属性但不可以访问实例属性,类方法访问类属性也是使用 “cls.” 的形式。