lass School(object):
def __init__(self, width, length):
self.width = width
self.length = length
@property
def cal_area(self):
return self.width * self.length
s = School(100, 100)
print(s.cal_area)
2. 类方法
类方法通过@classmethod装饰器实现,类方法和普通方法的区别是, 类方法只能访问类变量,不能访问实例变量。
# 访问实例变量
class Person(object):
def __init__(self, name, country):
self.name = name
self.country = country
@classmethod
def nationality(self):
print('Bigberg is %s.' % self.country)
p = Person('Bigberg', 'CN')
p.nationality()
# 输出
Traceback (most recent call last):
File "G:/python/untitled/study6/静态方法.py", line 31, in <module>
p.nationality()
File "G:/python/untitled/study6/静态方法.py", line 24, in nationality
print('Bigberg is %s.' % self.country)
AttributeError: type object 'Person' has no attribute 'country'
# 访问类变量
class Person(object):
country = 'Chinese' # 增加一个 全局属性/静态字段
def __init__(self, name, country):
self.name = name
self.country = country
@classmethod
def nationality(cls): # 这里将sefl 改为 cls
print('Bigberg is %s.' % cls.country)
p = Person('Bigberg', 'CN')
p.nationality()
# 输出
Bigberg is Chinese.
class Person(object):
def __init__(self, name, country):
self.name = name
self.country = country
def nationality(self):
print('Bigberg is %s.' % self.country)
Person.nationality(Person) # 需要一个参数
class Person(object):
country = 'Chinese' # 增加一个 全局属性/静态字段
def __init__(self, name, country):
self.name = name
self.country = country
@classmethod
def nationality(cls): # 这里将sefl 改为 cls
print('Bigberg is %s.' % cls.country)
Person.nationality() # 不需要参数
3. 静态方法
在类中的方法前面通过@staticmethod装饰器即可把其装饰的方法变为一个静态方法
普通的方法,可以在实例化后直接调用,并且在方法里可以通过self.调用实例变量或类变量,但静态方法是不可以访问实例变量或类变量的,一个不能访问实例变量和类变量的方法,其实相当于跟类本身已经没什么关系了,它与类唯一的关联就是需要通过类名来调用这个方法。
class Person(object):
def __init__(self, name):
self.name = name
@staticmethod
def speak():
print('someone is speaking chinese.')
# 静态方法在类中也不需要传入 self参数
静态方法是不能访问实例变量和类变量的
class Person(object):
def __init__(self, name):
self.name = name
@staticmethod
def speak(self):
print('%s is speaking chinese.' % self.name)
p = Person('Bigberg')
p.speak()
# 我们在 speak(self) 函数中传入 self
# 事实上以上代码运行会出错的,说speak 需要一个self参数,但调用时却没有传递,没错,当speak变成静态方法后,再通过实例调用时就不会自动把实例本身当作一个参数传给self了。
Traceback (most recent call last):
File "G:/python/untitled/study6/静态方法.py", line 26, in <module>
p.speak()
TypeError: speak() missing 1 required positional argument: 'self'
想让以上代码可以正常执行,有两种方法:
class Person(object):
def __init__(self, name):
self.name = name
@staticmethod
def speak(self):
print('%s is speaking chinese.' % self.name)
p = Person('Bigberg')
p.speak(p)
# 输出
Bigberg is speaking chinese.
- 在方法speak中去掉self,但这也意味着,不能通过self.调用实例中的其它变量了
class Person(object):
def __init__(self, name):
self.name = name
@staticmethod
def speak(): # 方法中已经没有 self 参数了
print('%s is speaking chinese.' % 'anyone')
p = Person('Bigberg')
p.speak()
#输出
anyone is speaking chinese.