编程语言
首页 > 编程语言> > python 类调用实例的方法

python 类调用实例的方法

作者:互联网

class A:
	def __init__(self,name,age):
		self.name = "shun"
		self.age = 18
	def eat(self):
		print (" i want to eat")
A.eat()

  报错, self 表示实例, A.eat()没有传入实例

class A:
    def __init__(self,name,age):
        self.name = "shun"
        self.age = 18
    def eat(self):
        print (" i want to eat")

a = A("shun",'12')
a.eat()

#把 实例a 作为self参数传给A object
A.eat(a)

 

class A:
    def __init__(self,name,age):
        self.name = "shun"
        self.age = 18
    def eat(self):
        print (self," i want to eat")

a = A("shun",'12')
a.eat()

#把 实例a 作为self参数传给A object
A.eat(a)


#使用类来调用类的方法, self参数必须要传入, 但是并不一定要求传入类A的实例,下面的方式也可以调用
A.eat("a person say")
<__main__.A object at 0x000001CFC670A430>  i want to eat
<__main__.A object at 0x000001CFC670A430>  i want to eat
a person say  i want to eat

  

标签:__,调用,name,python,self,age,实例,want,eat
来源: https://www.cnblogs.com/shunguo/p/15678470.html