Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Questions about class
#1
class FooBar:
  def init(self):
    print(self)
From the above example, i learn that i can't define a as the below code

a = FooBar()
a.init(42)
Otherwise it will have the below error
Error:
Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: init() takes 1 positional argument but 2 were given
I want to know when i should use
a = FooBar
and when i should use
a = FooBar()
Many thanks!
Quote
#2
Calling a.init(42) actually does this: FooBar.init(a, 42). Methods inside a class must use self as the first argument, but the self refers to the instance of the object that is calling the method. Any additional arguments must follow after self.

It is common practice to use __init__ to initialize an instance of the class. This gets called automatically when you create an instance.
class FooBar:
    def __init__(self, value):
        self.value = value   # Keeps a copy of initial value

a = FooBar(42)
print(a.value)
Output:
42
You will seldom use "a = FooBar". This sets a equal to Foobar and lets me do things like:
a = FooBar
b = a(42)
print(b.value)
print(type(b))
Output:
42 FooBar
You can imagine how confusing this could be with users of your code trying to find where class "a" is defined. That is not to say you would never do this sort of thing. for example, I have seen this kind of idea used to implement a case statement in python. Lets say I am reading in a spreadsheet and creating objects based on the value of one of the fields. I could write something like this:
if vehicle_type == 'Sedan':
      vehicle = Car(record)
elif vehicle_type == 'SUV':
      vehicle = SUV(record)
and on and on for dozens of different vehicle types
Instead you could create a dictionary of classes keyed by the vehicle type value

vehicle_classes = {'Sedan': Car, 'SUV': SUV …..)

vehicle = vehicle_classes[vehicle_type](record)
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Discord bot that asks questions and based on response answers or asks more questions absinthium 1 3,276 Nov-25-2017, 06:21 AM
Last Post: heiner55

Forum Jump:


Users browsing this thread: 1 Guest(s)