Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
def vs class
#1
Hi everyone,

I am self-learning python and just came across a question why I cannot rewrite the example on the book in another way.

The example on the book is >>>>
class Cat():
    def __init__(self, name):
      self.name=name

furball=Cat('Grumpy')
print('Our latest addition:', furball.name)

Our latest addtion: Grumpy


My way to rewrite it is >>>
def Cat(x)
    if x=='furbal':
      Print('Grumpy')

print('Our latest addition:',Cat('furball'))
Grumpy
Our latest addition: None
Reply
#2
In your second piece of code, there are three errors -
  1. No : at the end of line 1
  2. On line 2, you seem to have forgotten an 'l' - it should be
    if x=='furball':
  3. On line 3, print shouldn't be having a capital p
However, anyways your code isn't expected to work as you just print Grumpy, not define it under a variable and call it, and so the expected error.
You can use this :
def Cat(x):
    if x=='furball':
      addition = 'Grumpy'
    return addition
 
print('Our latest addition:',Cat('furball'))
pyzyx3qwerty
"The greatest glory in living lies not in never falling, but in rising every time we fall." - Nelson Mandela
Need help on the forum? Visit help @ python forum
For learning more and more about python, visit Python docs
Reply
#3
There's nothing to stop you from writing your code as a function rather that a class.
However if you decide to add more functionality, and use a class (for example new methods),
those will become available to any program that instantiated the class, automatically.
there are other benefits, such as scope. Forward referencing is a snap if using a class, a good
example of when this would be beneficial would be when using events. For example a button. The event attached to the button can reside anywhere within the class, but must precede a function.
Reply


Forum Jump:

User Panel Messages

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