How to make objects accessible from anywhere within it's class [closed] - python

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 8 years ago.
Improve this question
As a general strategy, is there a way to add objects to init, without initialization, while the code is being executed. For example, instead of:
class Test:
def __init__(self):
self.a = False
self.b = False
def set_values(self, in_boolean):
if in_boolean:
self.a = True
else:
self.b = True
Do this:
class Test:
def __init__(self):
self.a = False
def set_values(self, in_boolean):
if in_boolean:
self.a = True
else:
self.b = True
# This object is only created if this condition is
# met. Otherwise, this is not created in __init__.
Does one need to initialize any and all objects in __init__ if they want to save an object there?
If this is not possible, what is an alternative method for creating global objects that are created within a class method?
I'll explain a scenario when I would want to use this so as to better illustrate the question:
Say I am executing a method within a class. Depending on certain conditions, an object may or may not be generated within that class that I would like to be able to access from all other methods within the class. Because the object may or may not be created, I don't wish to initialize it in __init__.
To sum it up: If I want to 'save' an object on my class, do I need to initialize it in __init__?
EDIT
Ok so my problem was that I believed one only created "self." objects in init. As I understand it now, one can make a "self." object anywhere in the class, not just in init. This would make said object accessible from anywhere else in the class, which is ultimately what I am looking for here. Maybe the question should have been:
How to I make objects accessible from anywhere in it's class?

In Python, you don't need to 'declare' a variable before you use it at all. If you try to access a variable that doesn't exist, you can just wrap it in a try...except AttributeError and call it a day.
The __init__ on a class is just like any other method on Python, it doesn't have access to any sort of functionality that the others don't. The only difference is that it has the benefit of being automatically called whenever you instantiate your class, saving you the trouble of having to write a constructor-like class every time and call it manually.

Related

Python class fuction that takes self variable as argument [closed]

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 1 year ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I want to write a function that sets a self variable to None, but it feels very wrong to write a million functions for each variable.
I want to do something like:
class MyClass():
def __init__(self):
self.duck = None
self.dog = None
def makeduck(self):
self.duck = "Duck"
def makedog(self):
self.dog = "Dog"
def deleteVar(self,var):
self.var = None # or del self.var
I want to do this because the variables tend to be very large and I don't want to overload my ram so I have to delete some not needed vars depending on the context.
It is indeed possible.
Although having a clear separation between what should be program structure: variables, and data: text inside strings, Python allows one to retrieve and operate on variables or attributes given their name.
In this case, you will want to use the setattr and delattrcalls: both take an instance, an attribute name, given as textual data (a string), and operate on them like the corresponding assignment (self.var = xxx) and deleting (del self.var ). statements (but, as you intend to use, with "var" being a variable containign the actual attribute name).
def deleteVar(self, var):
# setattr(self, var, None). #<- sets attribute to None
delattr(self, var). # <- deletes attribute.
(for completeness: there is also the getattr call which allows attribute retrieval on the same bases)
That said: the memory usage of hard-coded variables, even if you have tens of them, will likely be negligible in a Python process.
Having tens of different "deleter" methods, however, would indeed be clumsy, and there are situations were your code might be more elegant by passing your attributes as data, as you intent.

What the purpose of creating class instance attibutes directly in the code [closed]

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 2 years ago.
Improve this question
Pyhon allows to create any class instance attribute just like new variable and you don't need to define them in class definition.
What's the purpose of that?
class MyClass:
def __init__(self):
pass
obj = MyClass()
obj.a = '1';
print(obj.a)
#>> 1
P.S.
found interesting example of such kind of usage
Can you use a string to instantiate a class
There dynamically created attributes used to store dynamically instatiated classes
The purpose of this is simplicity: There is no difference to accessing an instance inside or outside of a method. The object seen inside and outside of a method is completely equivalent, and by extension the same rules apply anywhere:
class MyClass:
def __init__(self):
print(self) # <__main__.MyClass object at 0x119636490>
self.b = 12 # assign to an instance
obj = MyClass()
print(obj) # <__main__.MyClass object at 0x119636490>
obj.b = 12 # # assign to an instance
Note that one can read and write attributes inside and outside methods, and these attributes are visible inside and outside of methods. In fact, Python has no concept of "inside" and "outside" of methods, aside from a few code-rewrites such as double-underscore name mangling.
This is both a result and the enabling feature to allow various inbuilt features of other languages to work without explicit support. For example, Python allows the equivalent of extension methods without extra syntax/functionality:
class MyPoint:
def __init__(self, x, y):
self.x, self.y = x, y
# Oops, forgot a repr!
def my_point_repr(self):
return f'{self.__class__.__name__}(x={self.x}, y={self.y})'
MyPoint.__repr__ = my_point_repr
print(MyPoint(1, 2)) # MyPoint(x=1, y=2)

use functions in a class - python [closed]

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 8 years ago.
Improve this question
I have a couple of functions defined in my code and I want to be able to call them in one of my class.
I want to pass one of their name as an argument so I can select the right function to call in my class.
I looked for such things on internet but what I found is how to call a function defined in a class inside the same or another class. I can't define my functions inside my class because they also call other functions
So there's not too much but there's my code :
class _fonction_use_:
def __init__(self,pos,function):
self.pos=pos
self.function=function
Where "function" would be the name of one of my functions defined outside the class.
So, if fonction_use belong to this class, I want something like fonction_use.function to return the function I would assigned it before.
Since functions are first class objects, you can pass them directly to your class.
def somefunc():
pass # do something
class MyClass(object):
def __init__(self, pos, function):
self.pos = pos
self.function = function
myclass = MyClass(0, somefunc)

Common practice of __new__ constructor? [closed]

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 8 years ago.
Improve this question
I know (?) about theory behind __new__ constructor in Python, but what I ask about is common practice -- for what purpose is this constructor really (!) used?
I've read about initializing immutable objects (the logic is moved from __init__ to __new__), anything else? Factory pattern?
Once again, please note the difference:
for what task __new__ can be used -- I am not interested
for what tasks __new__ is used -- I am :-)
I don't write anything in Python, my knowledge is from reading, not from experience.
Where you can actually answer the question: Common practice of new constructor?
The point of __new__ is to create an empty object instance that __init__ then initializes. Reimplementing __new__ you have full control of the instance you create, but you stop short of actually using the __init__ method to do any further processing. I can give you two cases where this is useful: automatic creation of methods and deserialization from disk of a class with a smart constructor. These are not the only ways you can solve these two problems. Metaclasses are another, more flexible way, but as any tool, you have different degrees of complexity you may want to get.
Automatic creation of methods
suppose you want to have a class that has a given set of properties. You can take control how these properties are initialized with code like this
class Foo(object):
properties = []
def __new__(cls, *args):
instance = object.__new__(cls, *args)
for p in cls.properties:
setattr(instance, p, 0)
return instance
class MyFoo(Foo):
properties = ['bar', 'baz']
def __init__(self):
pass
f=MyFoo()
print dir(f)
the properties you want are directly initialized to zero. You can do a lot of smart tricks, like doing the properties list dynamically. All objects instantiated will have those methods. A more complex case of this pattern is present in Django Models, where you declare the fields and get a lot of automatic stuff for free, thanks to __new__ big brother, metaclasses.
Deserialization from disk
Suppose you have a class with a given constructor that fills the fields of the class from an object, such as a process:
class ProcessWrapper(object):
def __init__(self, process):
self._process_pid = process.pid()
def processPid(self):
return self._process_pid
If you now serialize this information to disk and want to recover it, you can't initialize via the constructor. So you write a deserialization function like this, effectively bypassing the __init__ method you can't run.
def deserializeProcessWrapperFromFile(filename):
# Get process pid from file
process = ProcessWrapper.__new__()
process._process_pid = process_pid
return process

What's the best style, class method or global function? [closed]

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 4 years ago.
Improve this question
It's often the case that I write a class, along with helper functions that are intimately connected to that class. For my current, a Window class to wrap some win32api calls, along with functions to, say, find windows. Should those helper functions be globals in the given module, or should they be class methods of the Window class. That is, should I have, in my module:
class Window(object):
def __init__(self, handle):
self.handle = handle
...
...
#classmethod
def find_windows(cls, params):
handles = ...
return map(cls, handles)
with the usage being:
from window import Window
windows = Window.find_windows("Specialty")
or should I do:
class Window(object):
def __init__(self, handle):
self.handle = handle
...
...
def find_windows(params):
handles = ...
return map(Window, handles)
with the usage being:
from window import Window, find_windows
windows = find_windows("Speciality")
Put more succinctly: should the grouping be at the class-level (e.g. they would be static methods in Java) or at the module level?
The first approach has the advantage that in case you subclass Window you can override yourfind_windows method (unlike static methods in java). However, this would only be useful if overriding would eventually make sense, otherwise I think it looks nicer having it as a function.
Edit: If you have multiple ways of finding Window objects, it would make sense to have an additonal class called WindowFinder or WindowManager which encapsulates query/finding logic.
This is a pattern used in django where if your Window class is let's say a db model, you than have Window.objects pointing to a WindowManager. The window manager has methods for building sql queries.
Then, you can do things like:
Window.objects.all()
or
Window.objects.filter(name="Speciality")
If find_windows() doesn't need access or knowledge of the inner workings of your Window class I would just make it a global function. There's little to be gained by increasing the dependencies between separate pieces of code, especially when it basically just an issue of where the source is located.
If I understand correctly, your find_windows function creates a list of Window instances from a list of handles.
It behaves a constructor, therefore, I would make it a function and not a classmethod of the Window class. As I mentioned in a comment, it feels more natural that way, but it's just a hunch.
EDIT
#Ioan Alexandru Cucu 's answer made me ponder the case where you subclass your Window as, say, a SubWindow.
If find_windows (or as suggested create_windows) is a classmethod, it will return a list of SubWindow instances, whereas it would only returns Window instances if it were an independent function as I suggested.
This can be considered as an interesting feature, and it would then make sense to keep find_windows as a classmethod. I would still put some kind of comment explaining the rationale in the docstring or elsewhere.
<tl;dr>: that depends.

Categories