Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python classes
#1
Dear python users,

As a python newbie I started two months ago learning a bit of coding. By learning some topics of Python some questions came to my mind and I would like to ask here I someone could help me with this case(s). Now I am kind of assuming what the solution would be but I prefer doing it in the correct way avoiding frustrations in the future Big Grin .

The query:
Inside class objects, should I use the SELF argument only in the __init__ def?

For example:
class CountFromBy:
    
    def __init__(self, v: int=0, i: int=1):
        self.val = v
        self.incr = i

    def increase(self):
        self.val += self.incr

    def __repr__(self) -> str:
        return str(self.val)
And what is the function of "v" and "i" in the __init__ object? Should it be better to used the same initials as "val" behind the self argument?

Hopefully the query description is understandable, please let me know if additional information is needed.

Like to hear!
Reply
#2
Python_User Wrote:Inside class objects, should I use the SELF argument only in the __init__ def?
Normally, you need to use the self argument in every method definition except when they are class methods or static methods (defined with the @classmethod and @staticmethod decorators). The self argument represents the object instance when the method is called. Actually, you could use another word than 'self' for this argument, but 'self' is traditional and that's what other python programmers expect.

The variables v, i in this __init__() method are the counter's initial value and increment. I don't think these are very good names because the __init__ function is the main public interface of the class. A user will call for example co = CountFromBy(5, 2), so the meaning of these variables should be as explicit as possible. I would have used 'start' and 'step' because these names are used in the prototype of the well known range() function and every Python programmer will understand them immediately
class CountFromBy:
    def __init__(self, start=0, step=1):
        self.val = start
        self.incr = step
The annotations such as : int or -> str are not required in Python, although some people may consider that it makes a better documented code. It is a trend in today's Python to clutter the code with annotations. Personally, I don't want to sacrifice the 'informal' side of the Python language that makes it so flexible, so I prefer to avoid type annotations.
Reply
#3
Hi Gribouillis,

Thanks for your explanation.

Quote:The self argument represents the object instance when the method is called.
I don't understand this sentence, what do you mean with object instance? Because when you have multiple objects, how does the program know which self argument to invoke? Mostly I try to visualize definitions in my head, but with this self arguments it is difficult Confused .


I tried to modified the code to run it once and increase the start value with 1, but I got a TypeError: 'int' object is not callable.
class CountFromBy:
    
    def __init__(self, start=0, step=1):
        self.start = start
        self.step = step

    def increase(self):
        self.start += self.step

    def __repr__(self) -> str:
        return str(self.start)
        
x = CountFromBy(0, 1)
x.increase()
x.start()
Reply
#4
(Aug-01-2020, 09:46 AM)Python_User Wrote: I don't understand this sentence, what do you mean with object instance? Because when you have multiple objects, how does the program know which self argument to invoke? Mostly I try to visualize definitions in my head, but with this self arguments it is difficult
Can run the class with some added comment and a class attribute.
class CountFromBy:
    # class attribute or class varible both name are okay
    reset = 0
    def __init__(self, start=0, step=1):
        # instance attributes
        self.start = start
        self.step = step

    def increase(self):
        '''I am method in Class CountFromBy'''
        self.start += self.step

    def __repr__(self) -> str:
        return str(self.start)
Run.
>>> # 0 and 1 is set as default parameters so no need to add same vaules
>>> # Only if start step need other vaules than 0 or 1,then put those in
>>> x = CountFromBy()
>>> x.start
0
>>> x.step
1
>>> x.increase ()
>>> x.start
1
>>> x.increase ()
>>> x.start
2
>>> x.increase ()
>>> x.start
3
# Step is always the same
>>> x.step
1
>>> # Call __repr__
>>> x
3

>>> # Reset
>>> x.start = x.reset
>>> # Now back to start
>>> x.start
0
>>> x.step
1
>>> 
Reply
#5
Thank you for the response Snippsat.

I am sorry but the following I don't understand:

# class attribute or class varible both name are okay
Do you mean a class definition? I found it in the python (class) docs: https://docs.python.org/3/tutorial/classes.html

>>> x = CountFromBy()
>>> x.start
From the code above, how does python know to run the __init__ object? As it has as well the self.start in the increase object.

class Employee:

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay
        self.email = first + '.' + last + '@company.com'

    def fullname(self):
        return '{} {}'.format(self.first, self.last)

emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'User', 60000)

emp_1.fullname()
print(Employee.fullname(emp_1))
As well for this code above, how does the interpreter 'moves' through this code? How does python know to run the def __init__ if the code emp_1 = Employee('Corey', 'Schafer', 50000) invokes? Does the interpreter looks to the amount of arguments for each object?
Reply
#6
When you call the class name like a function, Python runs the __init__() method. When you call Employee(), you create an instance of the Employee class. This instance is initialized by calling automatically the __init__() method.
Reply
#7
I think the subject is getting clearer in my mind :).

So does this mean that you are limited to only one __init__ (function class)? Because when you make another function class python doesn't know where to refer right?
Reply
#8
(Aug-02-2020, 08:04 AM)Python_User Wrote: Do you mean a class definition? I found it in the python (class) docs: https://docs.python.org/3/tutorial/classes.html
No,i mean what reset = 0 is called.
class CountFromBy:
    reset = 0 # class attribute
    def __init__(self, start=0, step=1):
        self.start = start # instance attributes
They have different functionally a class attribute belongs to a class rather than a particular object.
class attribute is shared between all the objects of this class.
instance attribute belong to only one object,and are not shared between objects.
Python_User Wrote:From the code above, how does python know to run the __init__ object? As it has as well the self.start in the increase object.
__init__() run automatically when create instance object x.
Then get also start=0, step=1 set to these values,if was just start and step then need to give values when create a new instance objects.
If i give new arguments then the default values is no longer used.
>>> x = CountFromBy(10, 25)
>>> x.start
10
>>> x.step
25
>>> x.increase()
>>> x.start
35
>>> x.increase()
>>> x.start
60
>>> x.increase()
>>> x.start
85
Reply
#9
Actually Employee() calls a method named Employee.__new__(cls) to create a new INSTANCE of class Employee. Then it calls Employee.__init__(self) where "self" is the INSTANCE returned by the call to __new__. Both __new__ and __init__ are completely optional and Python automatically provides default methods for each that are inherited from the superclass. Most classes override the __init__ method, but overriding __new__ is fairly rare.

Stop using "function class". There is no such thing as a "function" class. A class in python is a collection of methods and class variables. A method looks a lot like a function, but it is associated with a class namespace instead of a module namespace. Because a class defines a namespace, each function and each variable can exist only once in the namespace. In this example __init__ gets defined twice. This does not generate any exceptions and the code runs fine, bit the second definition of __init__ quietly replaces the first. Though the class defines two methods, you can only access the last one that was defined. This is True of all "things" in the class namespace. The Doubleup namespace contains only one "__init__" and one "message" and one "classvar". Each instance has only one "punctuation".
class Doubleup:
    classvar = 'Hello'
    classvar = 'Goodbye'
    
    def __init__(self):
        self.punctuation = ','
        self.punctuation = '!'

    def __init__(self):
        self.punctuation = ';'
        self.punctuation = '?'

    def message(self):
        return f'Hello world{self.punctuation}'

    def message(self):
        return f'Goodbye world{self.punctuation}'

print(Doubleup().message())
Output:
Goodbye world?
Instances of a class also have a namespace. Each instance of class Employee can have a different first name and a different last name because each instance of Employee has it's own namespace. When I give Bob a raise (Bob.pay *= 1.05), I am using the "pay" from the "Bob" namespace, and it does not affect the "pay" in the "Alice" namespace.

The more common way to say all of this is that each Class has its' own methods and class variables, and each instance of a class has its' own instance variables.
Reply
#10
Ok, this is a bounce of information and difficult to understand.

class Doubleup:
    classvar = 'Hello'
    classvar = 'Goodbye'
     
    def __init__(self):
        self.punctuation = ','
        self.punctuation = '!'
 
    def __init__(self):
        self.punctuation = ';'
        self.punctuation = '?'
 
    def message(self):
        return f'Hello world{self.punctuation}'
 
    def message(self):
        return f'Goodbye world{self.punctuation}'
 
print(Doubleup().message())
From the code above:
- Why isn't the puntuaction defined as argument in the methods?
- What is the function of "f" in return f'Goodbye world{self.punctuation}'?
- What is the curly brackets function in return f'Goodbye world{self.punctuation}'?
- How knows python to refer to the question mark?? This is really difficult to understand for me at the moment...

Maybe the questions are dumb, but I am trying to understand it properly.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Classes rob101 4 527 Feb-05-2024, 06:51 PM
Last Post: rob101
  Understanding Python classes PythonNewbee 3 1,183 Nov-10-2022, 11:07 PM
Last Post: deanhystad
Sad Python classes PythonNewbee 4 1,046 Nov-09-2022, 01:19 PM
Last Post: deanhystad
  Inheritance vs Instantiation for Python classes mr_byte31 7 2,850 Oct-14-2021, 12:58 PM
Last Post: mr_byte31
  Understanding Python super() for classes OmegaRed94 1 1,828 Jun-09-2021, 09:02 AM
Last Post: buran
  Python Classes leodavinci1990 1 2,079 Nov-27-2019, 07:25 AM
Last Post: buran
  Using classes? Can I just use classes to structure code? muteboy 5 5,035 Nov-01-2017, 04:20 PM
Last Post: metulburr
  use of classes in python Lux 2 3,510 Aug-19-2017, 12:29 PM
Last Post: hbknjr
  python classes prsdll6 14 7,368 Aug-17-2017, 07:26 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020