无论是类属性还是类方法。 无法像普通的函数或者变量一样在类的外部直接使用。可以将类看作是一个独立的空间。那么类属性就是在类中定义的变量。类方法就是在类中定义的函数。
class Person:
name = '小张',
age = 24
class Person:
name = '小张',
age = 24
a = Person()
print(a.name)
b = Person()
print(b.name)
('小张',)
('小张',)
class Person:
name = '小张',
age = 24
print(Person.name)
print(Person.age)
Person.name = 'Jack'
Person.age = 25
print(Person.name)
print(Person.age)
('小张',)
24
--------------------------------
Jack
25
class Person:
name = '小张',
age = 24
a = Person()
print(a.name)
b = Person()
print(b.name)
b.name = 'jack'
print(b.name)
print(a.name)
('小张',)
------------------------
('小张',)
------------------------
jack
('小张',)
class Person:
name = '小张',
age = 24
a = Person()
b = Person()
print(a.name)
print(a.age)
print(b.name)
print(b.age)
Person.name = 'jack'
Person.age = 39
print(a.name)
print(a.age)
print(b.name)
print(b.age)
('小张',)
24
('小张',)
24
----------------------
jack
39
jack
39
class Person:
name = '小张',
age = 24
a = Person()
b = Person()
Person.city = "成都"
print(Person.city)
print(a.city)
print(b.city)
成都
成都
成都
class Person:
def __init__(self, name, age):
self.name = name,
self.age = age
class Person:
def __init__(self, name, age):
self.name = name,
self.age = age
def addCity(self):
self.city = "成都"
a = Person("jack", 34)
b = Person("jack", 34)
a.addCity()
print(a.city)
print(b.city)
成都
Traceback (most recent call last):
File "/Users/apple/Documents/重要文件/python3/python21.py", line 13, in
print(b.city)
AttributeError: 'Person' object has no attribute 'city'
class Person:
def __init__(self, name, age):
self.name = name,
self.age = age
def addCity(self):
self.city = "成都"
a = Person("jack", 34)
a.addCity()
print(a.city)
print(Person.city)
成都
Traceback (most recent call last):
File "/Users/apple/Documents/重要文件/python3/python21.py", line 12, in
print(Person.city)
AttributeError: type object 'Person' has no attribute 'city'
class Person:
name = "小王",
age = 34
a = Person()
a.name = "Alice"
print(a.name)
print(Person.name)
Alice
('小王',)
注意:示例变量和类变量可以同名。但是此时无法通过对象调用类属性。所以不推荐使用对象调用类属性
class Person:
name = "小王",
age = 34
a = Person()
b = Person()
a.city = "成都"
print(a.city)
print(b.city)
成都
Traceback (most recent call last):
File "/Users/apple/Documents/重要文件/python3/python21.py", line 10, in
print(b.city)
AttributeError: 'Person' object has no attribute 'city'
------------------------------
class Person:
name = "小王",
age = 34
a = Person()
b = Person()
a.name = 'jack'
print(a.name)
print(b.name)
jack
('小王',)
class Person:
def add(self, number):
sun = 100 + number
print("这是一个局部变量", sun)
a = Person()
a.add(100)
这是一个局部变量 200
局部变量只能在当前的类方法中使用。函数执行完之后局部变量就会被销毁。