Python:Error calling class variable in a staticmethod - python

I am trying to call a class variable within a staticmethod, but when I called I am getting an error "hello" is not defined. any advise ?
class hello:
random1 = []
#staticmethod
def sub(x):
hello.random1.append(x -1)
sub.__func__(2)
if __name__ == "__main__":
print(hello.random1)

hello doesn't exist as a global name until you dedent out of the class definition (at which point the class is created and assigned to the global name hello). Change the code to:
class hello:
random1 = []
#staticmethod
def sub(x):
hello.random1.append(x -1)
hello.sub(2)
so sub is invoked after hello exists, and it will work.

Related

Is there a way to access an attribute outside a class?

I want to access an attribute outside a class, but even after googling I don't see any similar solution for this particular problem.
class test():
def __init__(self) -> None:
pass
def testpy(self):
self.x = 'Hello world'
value = test().testpy.x
print(value)
>> AttributeError: 'function' object has no attribute 'x'
I think you are confused with what an attribute is.
In your code X is a local variable in the member function testpy. X exists only in that function, and is deleted upon function exit.
If you want a member, write self.x = 'Hello world'. This will create and store a data member called x. Additionally, when you write test().testpy().x you are calling the member function testpy() and are then attempting to call .x on the return result, which will obviously break.
I think you're confusing local scope, with class attributes, and global scope.
You can achieve your result in one of three ways:
Creating a class attribute to access
Using the return keyword to return local values
Using the global keyworld to create a globally scoped variable. Highly not recommended
class test:
def __init__(self) -> None:
self.x = "Hello world"
pass
def testpy(self):
self.x = "Hello world"
x = "Hello world"
global Y
Y = "Hello world - global"
return x
object = test()
value_via_objects_attribute = object.x
value_via_objects_method = object.testpy()
value_via_global = Y
print(value_via_objects_attribute)
print(value_via_objects_method)
print(value_via_global)
In your code, x is a local variable inside a function, not a class attribute. You can return that variable:
class test():
def __init__(self) -> None:
pass
def testpy(self):
x = 'Hello world'
return x
value = test().testpy()
print(value)
Please go through python class tutorial once more.
testpy is a function of class Test, it returns None in the above code. x is an attibute of class Test not function 'testpy'
class Test():
def __init__(self):
pass
def testpy(self):
self.x = 'Hello world'
t = Test()
t.testpy()
value = t.x
print(value)
I think you are confusing your testpy() function with your constructor - the init method. In python, you can initialize a new object by calling the class as if it were a function - ex, "value = test()". When you call this function, the init method gets called, and returns a new object (self). So to declare an attribute on self, in the init function (your constructor), you simply write "self.x = "Hello World".
The full solution to your problem is below.
class test():
def __init__(self):
self.x = 'Hello World'
value = test()
print(value.x)

See function stop from locating defined class in Python

I'd like to define a class inside a function (for testing purpose) and put a value into
a function variable:
def foo():
myvar = None
class myclass:
def run(self):
myvar = 5
mm = myclass()
mm.run()
print(myvar)
The above prints None
Is there any way other than global to make the myvar variable accessible from the class? The correct answer would print 5
It's not possible to assign a value to a variable outside the current scope without global. If you need to persist the value within the class you can define class variables instead. Example:
def foo():
class Class:
var_to_change = None
def run (self):
self.var_to_change = 5
print (Class.var_to_change)
instance = Class()
instance.run()
print (Class.var_to_change)
I haven't tested the above code but it should work in theory.

Python: Why does class variable get assigned?

Here is my code:
class MyClass:
def __init__(self):
self.value = 0
def set_value(self, value):
self.value = 5
def get_value(self):
return self.value
value = print("Hello")
a = MyClass()
The output is:
Hello
What I do not understand is why print("Hello") gets executed. When I create an instance of the class only the instance variable is set to 0. Why self.value = 0 calls value = print("Hello")?
Can someone explain me this behavior?
The code evaluates the class when you execute it, and calls the print to define the class variable value.
The below example shows that it's printed before the instanciation.
class MyClass:
def __init__(self):
self.value = 0
def set_value(self, value):
self.value = 5
def get_value(self):
return self.value
value = print("Hello")
print('hi')
a = MyClass()
#output
>>> Hello
>>>hi
It doesn't. That print is executed because it's at the class level itself; the body of a class is executed at the time the class is defined. You would get that output even if you never instantiated MyClass.
Don't let the indentation trick you. value is not an instance variable. value is a class variable because it is defined in the class's scope. It's the same as doing:
class MyClass:
value = print("Hello")
....
Which means that the call to print will run at class definition time. In other words, when Python defines MyClass it also defines all of the class level variables - including value. To define value, it then calls print, which is why Hello is printed before you create an instance of MyClass.
If you want only instances of MyClass to print Hello, put the variable definition inside of the class constructor.
Side note: The print function returns None, so it's seems a bit strange that your assigning the value to a variable. Perhaps you were looking for something like input instead?
It does not, drop a = MyClass() and it will print "Hello" anyway. It executes code in the body when a class is defined:
class MyClass:
print(2 * 2)
# prints 4

Changing Variables in Class from Other Classes (Python)

Say I have this code:
class hello_world():
def define_hello(self):
self.hello = "hello"
def say_hello(self):
print self.hello
class change_to_goodbye():
def __init__(self):
self.helloWorld = hello_world()
def hello_to_goodbye(self):
self.helloWorld.hello = "goodbye"
class other_class():
def __init__(self):
self.helloWorld = hello_world()
self.changeToGoodbye = change_to_goodbye()
self.helloWorld.define_hello()
self.changeToGoodbye.hello_to_goodbye()
self.helloWorld.say_hello()
oc = other_class()
Class hello_world has two methods, one that defines the variable hello and one that prints it. On the other hand, class change_to_goodbye tries to access the variable hello in class hello_world and changes it to goodbye. Class other_class should set the variable hello to "hello", change it to "goodbye", and print it on the screen.
I expected the output to be "goodbye" but I got "hello". Why isn't change_to_goodbye changing the variable of hello_world?
This is because your change_to_goodbye class stores its own hello_world object inside it. The hello_world object in changeToGoodbye is not the same as the hello_world object helloWorld. So in other_class when you do self.changeToGoodbye.hello_to_goodbye(), your helloWorld variable isn't being altered at all. What's being altered is changeToGoodbye's helloWorld object.
So: self.changeToGoodbye.helloWorld.say_hello() would return goodbye.
So to summarize:
class other_class():
def __init__(self):
self.helloWorld = hello_world()
self.changeToGoodbye = change_to_goodbye() #contains a different hello_world object
self.helloWorld.define_hello()
self.changeToGoodbye.hello_to_goodbye() #changes the hello_world object inside of changeToGoodbye
self.helloWorld.say_hello() #the unaltered helloWorld object
if you wanted to change the output of helloWorld, you could change the change_to_goodbye class's constructor so that its hello_world object is the one you just created.
class change_to_goodbye():
def __init__(self, hw):
self.helloWorld = hw
#other code
You are not changing class variable, you are changing instance variable.
By self.helloWorld = hello_world() you defines an hello_world instance let's called it A, and self.changeToGoodbye = change_to_goodbye() you defines an change_to_goodbye instance B which has an hello_world instance C.
Then self.helloWorld.define_hello() set A's variable as hello and self.changeToGoodbye.hello_to_goodbye() set C's variable as goodbye.
At last self.helloWorld.say_hello() will print A's variable, and you will get hello.

Python define class in function, the class canbe access global

abc.py, how to create b() in class a ?
class a(object):
bInst=b()
def start():
class b(obj):
pass
if __name=='__main__'
start()
But how to using variable, Here is the codes, it report 'myCls' is not defined.
class a(obj):
inst=myCls()
def start
tSuiteN="myCls"
exec('global tSuiteN')
str="class {}(object): pass".format(tSuiteN)
exec(str)
Make it global.
def start():
global b
class b(obj):
pass

Categories

Resources