Nested Function in a Class, Python - python-3.x

I am trying to have Nested function inside a class. Here is my coad
class big():
def __init__(self):
self.mas = "hello"
def update(self):
def output(self):
print(self.mas)
self.output()
thing = big()
thing.update()
However when it runs I get an error that output is not defined. How can i run the output function inside the update function?

Just call it as output(), without self. The way you've defined it, it basically is a local variable inside your update method, not an attribute of the class.
class big():
def __init__(self):
self.mas = "hello"
def update(self):
def output():
print(self.mas)
output()
thing = big()
thing.update()

Related

How to use the second parent class methods which is inheriting from an interface in python?

I am trying to implement an interface and this interface is taken by two concrete classes say class First and class Second, I have another class that takes these two classes as a parent class CO. The class CO makes a decision based on a flag to return which of the two inherited classes, so as to use their implementation.
from abc import ABC, abstractmethod
class common(ABC):
#abstractmethod
def firstfunction(self):
pass
#abstractmethod
def secondfunction(self):
pass
class First(common):
def __init__(self)-> boto3:
self.ert = "danish"
# self.username = kwargs["username"]
# self.password = kwargs["password"]
print("Inside First function")
def firstfunction(self):
print("My implementation of the first function in FIRST CLASS")
def secondfunction(self):
print("My implementation of the second function in FIRST CLASS")
class Second(common):
def __init__(self):
self.rty = "pop"
# self.session_id = kwargs["session_id"]
print("Inside Second function")
def firstfunction(self):
print("My implementation of the first function in SECOND CLASS")
def secondfunction(self):
print("My implementation of the second function in SECOND CLASS")
class CO(First, Second):
def __init__(self):
self.inst = self.jo()
def jo(self):
a = True
if a:
main_object = First()
return main_object
else:
main_object = Second()
I am instantiating and calling the methods
mymainclass = co()
objt = mymainclass
objt.firstfunction()
objt.secondfunction()
So my condition is if the flag a = True in the CO class then the Concrete class First implementation of the methods should be used and we should get the output like this:
Inside the First function
My implementation of the first function in FIRST CLASS
My implementation of the second function in FIRST CLASS
If the flag a = False in the CO class then concrete class Second should be used and we should get the output like this:
Inside the Second function
My implementation of the first function in FIRST CLASS
My implementation of the second function in FIRST CLASS
From the given code I am getting the following output for the flag a = False :
Inside the Second function
My implementation of the first function in FIRST CLASS
My implementation of the second function in FIRST CLASS
Can someone make this code work? What am I doing wrong? I know I can make a function that takes these two classes as variables and then return what I want based on a condition. But I want to use classes for the same
I would not inherit class CO from either First or Second because you want to end up with an object that is either an instance of class First or class Second. The most straightforward way of doing this is to define method __new__ which will give you more control over instance creation.
Keep all of your code the same (after fixing the obvious errors, such as boto3 not being defined) and changing class CO as follows:
class CO:
def __new__(cls):
a = True
if a:
main_object = First()
else:
main_object = Second()
return main_object
o = CO()
print(type(o))
Prints:
Inside First function
<class '__main__.First'>
If you want to better parameterize the instance creation (and simplify the code within __new__), then have variable a be an argument to CO:
class CO:
def __new__(cls, a):
return First() if a else Second()
o = CO(False)
print(type(o))
Prints:
Inside Second function
<class '__main__.Second'>
You could optionally have class CO have common as its base class to document that instantiating this class results in an instance that implements the common interface. But doing so will not result in enforcing the actual type that is returned by __new__:
class CO(common):
def __new__(cls, a) -> common:
# The Python interpreter is not type-checking what is returned:
#return First() if a else Second()
return []
o = CO(False)
print(type(o))
Prints:
<class 'list'>
You can also substitute a factory function for class CO:
def common_factory(a):
return First() if a else Second()
o = common_factory(False)
Note
If you want to ensure that classes that inherit from base class common must override both firstfunction and secondfunction to more closely emulate a pure interface as implemented in other object-oriented languages, then you should define these functions in common so that they raise an NotImplementedError exception:
class common(ABC):
#abstractmethod
def firstfunction(self):
raise NotImplementedError
#abstractmethod
def secondfunction(self):
raise NotImplementedError
Unfortunately, the enforcement is done at run time with its attendant surprises instead of at compile time as is done in other object-oriented languages.
Okay I think in this situation, CO class must come from common class and implement the first and second function. In the implementation, it will use the First or Second classes functions depends on the result of jo function. Here is the correct Co class code:
class CO(common):
def __init__(self):
self.inst = self.jo()
def jo(self):
a = False
if a:
return First()
return Second()
def firstfunction(self):
self.inst.firstfunction()
def secondfunction(self):
self.inst.secondfunction()
a = CO()
a.firstfunction()
a.secondfunction()
You can directly call the method you want by using the class name.
Unless you have some pressing reason to do this that you didn't include in your question, I would avoid this in favor of a factory function that returns either a First or Second instance depending on the inputs.
class common(ABC):
#abstractmethod
def firstfunction(self):
pass
#abstractmethod
def secondfunction(self):
pass
class First(common):
def __init__(self):
self.ert = "danish"
super().__init__(self)
def firstfunction(self):
print("My implementation of the first function in FIRST CLASS")
def secondfunction(self):
print("My implementation of the second function in FIRST CLASS")
class Second(common):
def __init__(self):
self.rty = "pop"
super().__init__(self)
def firstfunction(self):
print("My implementation of the first function in SECOND CLASS")
def secondfunction(self):
print("My implementation of the second function in SECOND CLASS")
class CO(First, Second):
def __init__(self):
super().__init__(self)
def use_first(self):
return True or False # whatever logic you have for determining this
def firstfunction(self):
if self.use_first():
return First.firstfunction(self)
else:
return First.firstfunction(self)

OOP - Python - printing instance variable too when I call static method alone

Here in this code I am just calling out my static method, but it prints my instance variable too. Could you please explain the reason for that, and how to avoid them being printed?
Like below:
I am a static Method
None
class Player:
def __init__(self, name = None):
self.name = name # creating instance variables
#staticmethod
def demo():
print("I am a static Method")
p1 = Player()
print(p1.demo())
As Python docs says:
Print objects to the text stream file, separated by sep and followed
by end. sep, end, file, and flush, if present, must be given as
keyword arguments.
So you can return your message in method and then just print it:
class Player:
def __init__(self, name = None):
self.name = name # creating instance variables
#staticmethod
def demo():
return "I am a static Method"
p1 = Player()
print(p1.demo())

Better way than pass the same argument among classes in Python

I have a question related to OOP but it should be implemented in Python.
I have a file user_inputs.py with all the user parameters.
In my main file, I have a function that is called first. This function is responsible to read all the user parameters and return a dictionary that will be used in the rest of the program.
My question is: what is the cleanest way to pass the user_parameters dictionary to all classes? I did it in 2 ways:
Method 1)
def read_user_parameters():
# code to open and read all parameters etc.
return user_parameters # returns a dictionary with all the user parameters
Class A():
def __init__(self, user_parameters):
self.user_parameters = user_parameters
Class B():
def __init__(self, user_parameters):
self.user_parameters = user_parameters
user_parameters = read_user_parameters()
object_A = A(user_parameters)
object_B = B(user_parameters)
I don't like this way because I have dozens of classes that need to pass this argument. So I thought to create a parent class with the user parameters:
Method 2)
Class User_parameters():
def __init__(self, user_parameters):
def read_user_parameters():
# code to open and read all parameters etc.
return user_parameters
Class A(User_parameters):
__init__(self, user_parameters):
super().__init__()
# self.user_parameters comes from the parent class now
Class B(User_parameters):
__init__(self, user_parameters):
super().__init__()
# self.user_parameters comes from the parent class now
object_A = A()
object_B = B()
I prefer method 2, however, when super() is initialized from Class A and Class B the function read_user_parameters() that reads the file will be called twice (multiply this by dozens of times). Is there a better solution than method 1 in which I call read_user_parameters() only once but doesn't need to pass the argument for all classes?
Thank you for your time.
Why not just have a single UserParameters class and two objects of the same class (Also class nameds are supposed to be camel-cases, not snake-cased)
#Single class for user parameters
class UserParameters:
def __init__(self, user_parameters):
self.user_parameters = user_parameters
def read_user_parameters(self):
# code to open and read all parameters etc.
return self.user_parameters
#Two objects
object_A = UserParameters("<params>")
object_B = UserParameters("<params>")

calling function inside nested class

I would like to call functions defined in a class (1) from a nested class (2) (class 2 defined in the class 1). something similar to the code below:
class firstclass(object):
def __init__(self, *args, **kwargs):
#some code and functions...
def afunction(self):
#some code
class nestedclass(tkinter.Frame):
def __init__(self, parent):
#some code
def anotherfunction(self):
#here I would like to call a function from the class firstclass from a button
self.abutton = tkinter.Button(self.parent, text = "blabla", command = firstclass.afunction)
self.abutton.grid(row = 0, column = 1,columnspan=1)
However I keep getting an error missing required positional argument self. how to give it this argument in the command option?
or any advice how to work around this issue?
thanks a lot in advance for all input

python 3 pygi webkit2 api how to call a variable inside __init__(self):

I got the class below and i need to call self.webview variable from a function inside another class. how do i achieve that.
class Window(w):
def __init__(self):
self.webview = WebKit2.WebView()
class anotherclass:
def send_js(js):
w = self.webview <-- cant get this to match
w.run_javascript(str(js))
class anotherclass:
js = "some js"
class Window(w):
def __init__(self):
self.webview = WebKit2.WebView()
self.webview.run_javascript(str(anotherclass.js))
i was doing it with the wrong approach the above seems to work for me, i can also put js variable inside a function.

Resources