Python无法分配对象变量

时间:2018-10-10 18:59:30

标签: python oop

我在创建类实例时尝试通过函数分配变量,但是它不起作用。

class Test:
    def __init__(self, l):
        self.l = l
        self.func(self.l) # or I tried self.func(l)
        self.z = None
        self.y = None

    def func(self, l):
        self.z = l  # doesn't work
        self.y = 123 # doesn't work

x = Test('test')
print(x.z) # = None
print(x.y) # = None

有人可以解释一下吗,欢迎链接!

3 个答案:

答案 0 :(得分:1)

%macro run_query(count); %do i=1 %to &count; // random logic proc sql; select count(*) from random_tbl where some_filtering_condition="&i"; quit; %end; %mend create; %run_query(10) 定义self.zself.y后,您将None重新定义为func。摆脱self.z

中的self.y__init__
class Test:

    def __init__(self, l):
        self.l = l
        self.func(self.l) # or I tried self.func(l)
        # These are redefining the variables, comment out
        # self.z = None
        # self.y = None

    def func(self, l):
        self.z = l  
        self.y = 123 

答案 1 :(得分:0)

为此,您只想让您的=GOOGLEFINANCE()不需要传递,因为我们的函数可以从func(self)调用self.l,也不需要__init__,那么我们可以只需调用self.func(self.l)即可使用func,然后它将更改x.funcx.x

的值
x.y

答案 2 :(得分:-1)

Python依赖于制表符/空格缩进,这应该可行。

class Test:
    def __init__(self, l):
        self.l = l
        self.func(self.l)  # or I tried self.func(l)
        self.z = None
        self.y = None

    def func(self, l):
        self.z = l  # doesn't work
        self.y = 123  # doesn't work


x = Test('test')
print(x.z)  # = None
print(x.y)  # = None