Skip to main content
 首页 » 编程设计

python之在 __init__ 中使用类方法

2025年05月04日10落叶

我有以下类(class),我想在该类(class)的 __init__ 中使用方法 location_change 。有没有办法做到这一点?我在下面使用的示例是一种简化,但我需要做的是使用类方法来转换一些构造函数数据。这可以在 python 中完成吗?

class dummy: 
 
    def __init__(self): 
 
        self.location = 'USA' 
        print(self.location) 
 
        location_change() 
        print(self.location) 
 
    def location_change(): 
 
        self.location = 'UK' 
 
 
first_dummy = dummy() 

请您参考如下方法:

当然可以!

self.location_change() 

类中的每个方法都应至少接受一个参数,通常称为 self。

def location_change(self): 

python中oop的入门教程 http://www.voidspace.org.uk/python/articles/OOP.shtml

文档 http://docs.python.org/tutorial/classes.html