This question already has answers here:
What do __init__ and self do in Python? [duplicate]
(18 answers)
Closed 3 years ago.
I am going through the book "Problem Solving with Algorithms and Data Structures using Python"
In the chapter for Queues there is a printer simulation with the Printer class.
here is the definition of Printer class:
class Printer():
def __init__(self, ppm):
self.pagerate = ppm
self.currentTask = None
self.timeRemaining = 0
My question is that how are the instance variable not present in parameter but still defined (e.g. currentTask and timeRemaining)?
Is it a practice in Python and is there any other better way to do this?
From the documentation https://docs.python.org/3/tutorial/classes.html#class-objects
The instantiation operation (“calling” a class object) creates an
empty object. Many classes like to create objects with instances
customized to a specific initial state. Therefore a class may define a
special method named __init__(), like this:
def __init__(self):
self.data = []
Also Instance variables vs. class variables in Python
You don't need to pass values for all parameters. By writing self.variable_name we automatically create instance variables. They don't need to be initiated with passed values. You can initiate them with None values.
Related
This question already has answers here:
When should I be using classes in Python?
(6 answers)
What is the purpose of the `self` parameter? Why is it needed?
(26 answers)
Closed 8 months ago.
What's the point of creating classes and self in python? Like:
class ThisIsClass(self):
def Func():
self.var+=1
ThisIsClass()
Is it necessary to use them?
It becomes necessary to pass self argument to the functions of your class. however, your code has several problems like the initialization of var variable. You need a constructor __init__ to create the variable, after that, you will be able to modify it:
class ThisIsClass:
def __init__(self, value=0):
self.var = value
def Func(self):
self.var+=1
c = ThisIsClass()
c.Func()
print(c.var)
In the above code, the class is instantiated as an object and stored in the variable c. You can assign an initial value to var by passing an argument to the object creation, like: c = ThisIsClass(89)
Output:
1
It has to do with the right structure of programming in python. No you dont need them 100% but if you want to have a nice and clean code I would propose you to get used of them. Also when the self is declared inside the brackets after the function name, that function can retrieve (and make available) the variable (self.variable) from and to wherever inside that class.
This question already has answers here:
How do I pass a variable by reference?
(39 answers)
Closed 2 years ago.
I want to create a Python class that can:
Take a variable as an argument when instantiating
Store the value of the variable in an attribute
Store the current value of the variable whenever "update()" method is used.
The code below did not work as intended. How can I update the value of the attribute through a method call, keeping in mind that it must work for arbitrary variables?
class MyObject():
def __init__(self,data):
self.data = data
def update(self):
self.data = data
value = 0
dataobject = MyObject(value)
value = 1
dataobject.update() #NameError: name 'data' is not defined
Pass by reference doesn't work the way you want in Python for int and other basic types (different story for lists and other types of objects, but I'll just answer the question you asked).
I don't really recommend this approach, but you could do this with the Global keyword:
class MyObject():
def __init__(self,data):
self.data = data
def update(self):
global value # only change is this
self.data = value
value = 0
dataobject = MyObject(value)
value = 1
dataobject.update()
print(dataobject.data) # prints 1
objects in Python don't have private attributes, so you could directly set the value:
dataobject.data = 1
Neither of these strike me as best practices, but I would have to know more about what you are trying to do in order to give you the best advice. Note that if you plan on having a bunch of instances of MyObject, trying to sync them up with a single global value may get out of hand. I would advise a new question with more info about what you are trying to do and someone will give the the best approach.
This question already has answers here:
What is the difference between a function, an unbound method and a bound method?
(6 answers)
Closed 2 years ago.
I am switching from MATLAB to Python and numpy and I would like to know if there is any difference between the option to define a class method and the option to the function to a class field (instance variable)? Here is the example:
class MyClass:
def __init__(self, a):
self.a=a #some variable
def add(self,b):
return self.a+b
vs
class MyClass:
def __init__(self, a):
self.a=a #some variable
self.add = lambda b: self.a+b
It works in both cases when I call
my_object=MyClass(2)
print(my_object.add(2)) #prints 4
Are there any differences between these two approaches? Any best practices/downsides?
To me, the first one feels more "proper OOP", but the second one feels more flexible. Or, maybe, the definitions are identical, because of the way Python works under the hood?
The second one can't be overridden and takes a lot more space, because there's a separate function in every instance's __dict__ instead of one function in the class __dict__. (Instance method objects are created and reclaimed on the fly if you do it the normal way, or optimized out entirely in many cases depending on Python version.)
This question already has answers here:
Printing all instances of a class
(8 answers)
Closed 9 years ago.
Okay, so what I am trying to do is to create a function that will find an object instance based on the value of a specific attribute that all objects of the class share. Essentially, I want Python to search through the specific attribute of each instance of the class, and check it against another value, and if it finds a match to do some stuff. In pseudocode:
for each instance of Class:
if search_keyword is in instance.attribute:
do some stuff
found = True
if found is True:
tell_user("Found instance!")
If more detail is required on the nature of my inquiry, then:
What I am doing is essentially using the object as an extended dictionary. I have multiple attributes attached to the object, and I want to search through them. I am essentially using it as a storage container, which I need to search through.
If there is a better way to store said information other than objects, please share.
I'm essentially using it as a dictionary with multiple keys.
You could do this easily enough by having a class attribute which is a list of all instances of that class ever created, and having the __init__ of each instance of the class add the instance to the list.
class Foo(object):
list_of_all_foos = []
def __init__(self):
Foo.list_of_all_foos.append(self)
Then to search all the Foo instances you've created:
for foo_instance in Foo.list_of_all_foos:
if search_keyword is in foo_instance.attribute:
do some stuff
found = True
if found is True:
tell_user("Found instance!")
Alternatively, to do this with a class method, which might be a little more idiomatic:
class Foo(object):
list_of_all_foos = []
#classmethod
def create_foo_and_add_to_list(cls, *args, **kwargs):
new_foo = cls(*args, **kwargs)
Foo.list_of_all_foos.append(new_foo)
return new_foo
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?