Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Is there a difference in the two ways of calling a static method in the same class shown below?
class MyClass:
def __init__(self):
self.do_something() #or MyClass.do_something()?
#staticmethod
def do_something():
pass
More specifically, particularly in the cases of refactoring (changing class name) and inheritance (as static methods can be inherited and overridden in Python)?
I can only think of one situation in which it would make a difference; what about when you inherit from MyClass? Compare:
>>> class MyClass(object):
def __init__(self):
self.do_something()
#staticmethod
def do_something():
print "Base class"
>>> class SubClass(MyClass):
#staticmethod
def do_something():
print "Sub class"
>>> s = SubClass()
Sub class
with:
>>> class MyClass(object):
def __init__(self):
MyClass.do_something()
#staticmethod
def do_something():
print "Base class"
>>> class SubClass(MyClass):
#staticmethod
def do_something():
print "Sub class"
>>> s = SubClass()
Base class
This is a contrived example, but you should consider what you think the appropriate behaviour should be.
Your example of refactoring to change the class name is a good one, too; self doesn't have to be updated whenever you rename the class, whereas if you have explicit MyClass references you have to update them all (a good IDE will do this for you, but if you can avoid it that's better).
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
When I write the __init__ method and assign attributes, can I access those attributes in other methods (functions) that I write in that class? If so, how is it done?
I've googled this but couldn't find an answer. I Haven't been able to wrap my head around this one.
Use self:
class MyClass:
def __init__(self):
self.name = 'John'
def other_method(self):
print(self.name)
other_method will print "John".
When you make a class and set an instance (like first_class = MyClass()) the def __init__(self): is run or initialised. Any variables in there, like self.name are able to be accessed from within the class and its functions, as well as when you use a class in another program. self kinda attaches that variable to that class.
Basically using Allure's example:
class MyClass:
def __init__(self):
self.name = "John"
def show_name(self):
print(self.name)
Then use MyClass's name outside of class, in a program:
firstClass = MyClass()#Initialise MyClass and its variables
print(firstClass.name)
Or:
firstClass= MyClass()
firstClass.show_name()
Both output:
'John'
(still putting up this answer for others, hope you don't mind :) )
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I'd like to know what's the best way to organize a class in Python as checking on previous questions here I didn't find exactly what I needed. Let's say I have this class:
class A():
def __init__(self):
self.data = #A pandas dataframe I get from an online API
I have then many functions inside this class which I'd like to organize. All these functions will need the Dataframe contained in self.data as parameter.
I thought to create a subclass for every group of functions but I didn't find a way to then refer to self.data from inside the subclass.
I found then online that I could organize the functions in different modules. However how to I pass the Dataframe in self.data as parameter to the functions? Let's say function1 is defined as following:
def function1(self):
print (self.data)
If the function was defined inside the class, I could do this:
x = A()
x.function1()
and get the print without passing self.data as parameter. How would I do this if a function is defined in another module and I import it in the main class without passing self.data as parameter every time? Thanks in advance.
EDIT:
If I do:
class A():
def __init__(self):
self.x = 1
self.b = self.B()
class B(A):
def print(self):
print(self.x)
I get an error saying "A is not defined"
I like your approach to create subclasses for each group of methods. First start with a base class which stores your data
class DataBase:
def __init__(self, data):
self._data = data
Then write your different groups of methods ...
class GroupB(DataBase):
def func_b1(self):
return self._data
def func_b2(self):
return self._data
class GroupA(DataBase):
def func_a1(self):
return self._data
def func_a2(self):
return self._data
... and finally collect all these groups together
class MyData(GroupA, GroupB):
pass
>>> d = MyData(123)
>>> d.func_a1()
123
>>> d.func_b2()
123
I hope this helps you.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
class A:
def __new__(cls):
return super(A,cls).__new__(cls)
No, it doesn't. It creates an instance of what you want.
Let's split down all your statements.
First, we declare a new class A:
class A:
By default, all classes inherit from object, so your declaration is the same as:
class A(object):
Next, you overwrite the definition for __new__:
def __new__(cls):
This is a function that takes the class object you want to instantiate.
Next, we call our base's class __new__ method:
super(A, cls) # This refers to the base class of A, which is object
.__new__(cls) # Calls object.__new__(cls), with cls being the class you want to instantiate
object.__new__ does the right job, in fact you can pass in any class you want and it will correctly instantiate it.
So, your A.__new__ is just a delegate to object.__new__, so really, your A.__new__ is completely useless, you can remove it and everything will work the same.
Having said that, when you do A(), this will trigger A.__new__(A), which will trigger object.__new__(A), so you'll end up with an instance of A.
If you were to have the following class:
class B(A):
def __new__(cls):
super(B, cls).__new__(cls)
The flow would be the same.
B() would trigger B.__new__(B) which would trigger A.__new__(B), which would trigger object.__new__(B), so you'd end up with an instance of B
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm working on a project where being able to discover the order of declaration of functions within a class would be quite useful. Basically, I'd like to be able to guarantee that all functions within a class are executed in the order they are declared.
The end result is a web page in which the order of the output of the functions matches the order in which the functions are declared. The class will inherit from a generic base class that defines it as a web page. The web application will dynamically load the .py file.
class Register(object):
def __init__(self):
self._funcs = []
def __call__(self, func):
self._funcs.append(func)
return func
class MyClass(object):
_register = Register()
#_register
def method(self, whatever):
yadda()
# etc
from types import MethodType, FunctionType
methodtypes = set((MethodType, FunctionType, classmethod, staticmethod))
def methods_in_order(cls):
"Given a class or instance, return its methods in the order they were defined."
methodnames = (n for n in dir(cls) if type(getattr(cls, n)) in methodtypes)
return sorted((getattr(cls, n) for n in methodnames),
key=lambda f: getattr(f, "__func__", f).func_code.co_firstlineno)
Usage:
class Foo(object):
def a(): pass
def b(): pass
def c(): pass
print methods_in_order(Foo)
[<unbound method Foo.a>, <unbound method Foo.b>, <unbound method Foo.c>]
Also works on an instance:
print methods_in_order(Foo())
If any inherited methods were defined in a different source file, the ordering may not be consistent (since the sort relies upon each method's line number in its own source file). This could be rectified by manually walking the class's method resolution order. This would be a fair bit more complicated so I won't take a shot here.
Or if you want only the ones directly defined on the class, which seems like it might be useful for your described application, try:
from types import MethodType, FunctionType
methodtypes = set((MethodType, FunctionType, classmethod, staticmethod))
def methods_in_order(cls):
"Given a class or instance, return its methods in the order they were defined."
methodnames = (n for n in (cls.__dict__ if type(cls) is type else type(cls).__dict__)
if type(getattr(cls, n)) in methodtypes)
return sorted((getattr(cls, n) for n in methodnames),
key=lambda f: getattr(f, "__func__", f).func_code.co_firstlineno)
This assumes a new-style class.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What is the main difference between class and def in python? Can a class in python interact with django UI (buttons)?
class is used to define a class (a template from which you can instantiate objects).
def is used to define a function or a method. A method is like a function that belongs to a class.
# function
def double(x):
return x * 2
# class
class MyClass(object):
# method
def myMethod(self):
print ("Hello, World")
myObject = MyClass()
myObject.myMethod() # will print "Hello, World"
print(double(5)) # will print 10
No idea about the Django part of your question sorry. Perhaps it should be a separate question?
class defines a class.
def defines a function.
class Foo:
def Bar(self):
pass
def Baz():
pass
f = Foo() # Making an instance of a class.
f.Bar() # Calling a method (function) of that class.
Baz() # calling a free function