acceptable use of python __init__ method [duplicate] - python

This question already has answers here:
Python - Why call methods during __init__()
(3 answers)
Closed 6 years ago.
I wanted to call class member functions to initialize the class members completely in init. items_left and rat_initialize are the member functions I am using to initialize all the members of the class instance correctly. Is it alright to do so?
class Maze:
""" A 2D maze. """
# Write your Maze methods here.
def __init__(self,maze,rat_1,rat_2):
self.maze = maze
self.rat_1 = rat_1
self.rat_2 = rat_2
self.num_sprouts_left = 0
self.items_left(maze)
self.rat_initialize(maze,rat_1,rat_2)

Yes you can do it. When __init__ is called, the object is already instantiated by this point all the methods are available.
Actual object instantitation takes place in __new__ and __init__ is only called after it. You have accesss to other functions from inside __init__.

Related

What is the name of functions defined under classes? [duplicate]

This question already has answers here:
What's the difference between a method and a function?
(41 answers)
Closed last year.
Below is a simple class, which is having one method/function in it
class Test():
def f(self):
return "function or method"
What should I call f() here - a method or a function?
From python official document's glossary:
method
A function which is defined inside a class body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self). See function and nested scope.
I'd say that is a method, since it is associated with the object of the class that it belongs to. I extracted the information from here.

Why is the staticmethod decorator necessary? [duplicate]

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

Real word simulation of a Printer using Queue in Python [duplicate]

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.

Define class functions in different source files? [duplicate]

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)

why is defining an object variable outside of __init__ frowned upon? [duplicate]

This question already has answers here:
Instance attribute attribute_name defined outside __init__
(6 answers)
Closed 5 years ago.
I sometimes define an object variable outside of __init__. plint and my IDE (PyCharm) complain.
class MyClass():
def __init__(self):
self.nicevariable = 1 # everyone is happy
def amethod(self):
self.uglyvariable = 2 # everyone complains
plint output:
W: 6, 8: Attribute 'uglyvariable' defined outside __init__ (attribute-defined-outside-init)
Why is this a incorrect practice?
Python allows you to add and delete attributes at any time. There are two problems with not doing it at __init__
Your definitions aren't all in one place
If you use it in a function, you may not have defined it yet
Note that you can fix the above problem of setting an attribute later by defining it in __init__ as:
self.dontknowyet = None # Everyone is happy

Categories

Resources