python 面向对象,类的方法和变量

类方法

实例方法

class Person:
country = 'China'
def __init__(self,name,sex):
#构造函数,
# print('self的内存地址,',id(self))
self.name = name
self.sex = sex
self.__zl = 200
self.cry()
def run(self):
print('%s 在run..' % self.name)
def fly(self):
print(' %s fly' % self.name)
def cry(self):
print('%s 哇哇哇哇' % self.name)
#实例方法
def say(self):
print('my name is %s,sex is %s' %(self.name,self.sex))
print('%s 斤'%self.__zl)
print('我的国籍是 %s' % self.country)
print('我的年龄是 %s' %self.age)
公共的方法,直接可以通过类名来调用
不需要实例化,通过实例也可以调用
import time
class Person:
country = 'China' 类方法公共方法
def __init__(self,name,sex):
#构造函数,
# print('self的内存地址,',id(self))
self.name = name
self.sex = sex
ces=Person('ces','123')
print(ces.country)

ces=Person('ces','123')
ces.country='dssd' 类变量的修改值的方法
print(ces.country)

类方法
之前说了实例方法需要实例化才能调用
类方法可以直接调用不需要实例化
import time
class Person:
country = 'China'
def say(self):
print('my name is %s,sex is %s' % (self.name, self.sex))
print('%s 斤' % self.__zl)
print('我的国籍是 %s' % self.country)
print('我的年龄是 %s' % self.age)
@classmethod 这种代表类方法
def putonghua(cls):
print(cls.country)
print('会说普通话')
@staticmethod
def suanuga():
print('suanuga')
Person.putonghua() #不需要实例化调用
Person.suanuga()
xh = Person()      也可以通过实例化调用
xh.putonghua()
使用场景,你定义的变量,这个方法不会用到,也不会调用其他的函数这种场景,只调用这一种

静态方法
import time
class Person:
country = 'China'
def say(self):
print('my name is %s,sex is %s' % (self.name, self.sex))
print('%s 斤' % self.__zl)
print('我的国籍是 %s' % self.country)
print('我的年龄是 %s' % self.age)
@classmethod 这个字段代表静态方法
def putonghua(cls):
print(cls.country)
print('会说普通话')
@staticmethod
def suanuga():
print('suanuga')
# Person.putonghua()
Person.suanuga() 调用的方法,每个人都能指挥这个方法
属性方法 
一个看起来像变量的方法。

原文地址:https://www.cnblogs.com/weilemeizi/p/14536151.html