This question already has answers here:
Define a method outside of class definition?
(5 answers)
Closed 4 years ago.
Is it possible (preserving all the class functionality) to write the class functions in separate files?
Below is an example:
TestClass.py:
class MyClass():
def __init__(self, param1=1, param2=2, param3=3):
self.param1, self.param2, self.param3 =param1, param2, param3,
def ClassFun1(self, param1=2):
return param1**2/self.param2
TestClass2.py:
def ClassFun2(self, param1=3):
return param1*3/self.param2
Next, following this answer, I compile both files (I am too lazy to use import), create a class variable and try to use ClassFun2:
x=MyClass()
x.myMethod=ClassFun2
x.myMethod(2)
As a result, I get an error, since self in ClassFun2 is treated as a parameter, rather than class itself:
AttributeError: 'int' object has no attribute 'param2'
Is it possible to split class definition into several source files? It is possible in C++ and this is actually very convenient when working as a team.
The variable x is an object of the class, not the class itself. You need to do:
x = MyClass
x.myMethod = ClassFun2
Notice that I didn't put () after MyClass. That returns the class itself, it doesn't return an instance of the class.
Then you need to create an instance to execute the method:
y = MyClass()
y.myMethod(2)
Related
This question already has answers here:
Does the #staticmethod decorator do anything?
(2 answers)
Closed 3 years ago.
Given that the following code runs without error, why is the staticmethod decorator necessary? What is it actually doing?
class Foo:
def say_hi(name):
print(f'Hello {name}.')
#staticmethod
def say_bye(name):
print(f'See ya later, {name}.')
my_name = 'Bar...t'
Foo.say_hi(my_name)
Foo.say_bye(my_name)
Static methods, much like class methods, are methods that are bound to a class rather than its object.
They do not require a class instance creation. So, they are not dependent on the state of the object.
The difference between a static method and a class method is:
Static method knows nothing about the class and just deals with the parameters.
Class method works with the class since its parameter is always the class itself.
https://www.programiz.com/python-programming/methods/built-in/staticmethod
This question already has answers here:
How to get the caller class name inside a function of another class in python?
(6 answers)
Closed 4 years ago.
I am editing some code that is being called by another system that I do not control. This system initializes my class from a few different places. I need to perform different things depending on where my class is called from.
Is there a way I can find where my object is being initialized?
A.py:
class InitializerA:
def calling_function(self):
Called()
class InitializerB:
def calling_function(self):
Called()
B.py:
class Called:
def __init__(self):
# I want to know here whether it is being called by InitializerA or InitializerB
I was able to find the answer by modifying the method given in this question:
How to get the caller class name inside a function of another class in python?
The inspect library helped me inspect the call stack.
You could pass the class initializing it as an parameter to Called i.e:
class class InitializerA:
def calling_function(self):
Called(self.__name__)
class Called:
def __init__(self, initializer):
self.initializer = initializer
This question already has answers here:
Overriding a static method in python
(3 answers)
Closed 6 years ago.
Suppose we declare a static method with same name in different classes. Is it possible?
If it is, then how and which function will be called?
class abc:
#staticmethod
def xyz():
print 'class_abc'
class abc1:
#staticmethod
def xyz():
print 'class_abc1'
class abc2:
#staticmethod
def xyz():
print 'class_abc2'
So what's the output and how we can call different functions of different classes?
You are having three classes with xyz() function in each class. But there is no relationship in these classes as they are not inheriting each other. So the answer is simple: xyz() will be called of the class which is calling the method.
For example: abc.xyz() will call the xyz() function of abc class. Similarly you can make call to ab1 and abc2's function as: abc1.xyz() and abc2.xyz().
You seem to be misunderstanding things. Classes introduce a separate namespace for themselves so, it is completely possible to create functions with the same name in different classes. These functions are not related in any other way other than their similar name.
Running <classname>.xyz() simply calls xyz() and prints the corresponding message.
Even if there was a relationship between the class, i.e a sub-classing relationship of the form:
class abc:
#staticmethod
def xyz():
print 'class_abc'
class abc1(abc):
#staticmethod
def xyz():
print 'class_abc1'
class abc2(abc1):
#staticmethod
def xyz():
print 'class_abc2'
The most recent definition of xyz will override previously existing entries for it and the effect would be the same, that is abc2.xyz() would print class_abc2, abc1.xyz() prints class_abc1 and so on.
Also, do note, you're using Python 2.x but aren't actually inheriting from object. This won't create a class in the sense most people are aware with today, take a look at What is the difference between old style and new style classes in Python? to get a better idea of what this entails.
Suppose we declare a static method with same name in different is it possible?
Yes
If it is possible then how and which function will be called.?
It's possible because classes have their own scope. Python treats each static method in your example differently. And even if your classes where related, such as in #Jim Fasarakis-Hilliard example, the current method would override the last method.
Each method will be called uniquely because each class is unrelated in your example(except for all of the classes being of type class).
This question already has answers here:
How to avoid having class data shared among instances?
(7 answers)
Closed 9 years ago.
i just have a puzzling question abou class attributes in python.
consider the following class below:
class A:
__lst = []
def add(self, str):
self.__lst.append(str)
print len(self.__lst)
i tried to make two instances x and y and i got this:
>>> x = A()
>>> x.add('aaa')
1
>>> x.add('bbb')
2
>>> y = A()
>>> y.add('aaa')
3
>>> y.add('bbb')
4
i was expecting that the instance of y will have a separate copy of the list attribute but it seems that the list just gets bigger even if you use another object to add elements to the list. it's simply weird.
can anybody please enlighten me on this matter?
thanks a lot in advance for your help. :-)
If you define an attribute inside of the class body then it will be a class attribute, and it will be shared by all instances. In your code self.__lst is going to be a reference to A.__lst.
To have a separate list for each attribute, define it as self.__lst inside of the __init__() function:
class A(object):
def __init__(self):
self.__lst = []
def add(self, s):
self.__lst.append(s)
print len(self.__lst)
In addition to the change referenced above, I also made some minor modifications so that your code follows some Python best practices: inheriting from object (new-style class) and not using str (or any other built-in name) as a variable name.
Variables declared inside a class but not by means of self are class-level properties (like your __lst). They are equivalent to Java's static. If you want your property to be unique for all instances, you need to declare them via self (i.e., self.__lst).
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between #staticmethod and #classmethod in Python?
I am learning OOP in python and came to know about these two methods
It seems that the difference in terms of syntax is that class methods are implicitly passed the class they belong to as their first parameter
class Circle:
all_circles = [] # class variable
#staticmethod
def total_area():
for c in Circle.all_circles: # hardcode class name
# do somethig
#classmethod
def total_area(cls):
for c in cls.all_circles: # no hardcode class name
# do something
I see class method as more flexible since we don't hardcode the class
Question:
- Is it even a question which one is better? #staticmethod or #classmethod?
- what are the scenarios suitable to use of each one of these methods?
A classmethod gets passed the class 'cls' that it was called upon. For more details see: What is the difference between #staticmethod and #classmethod in Python?