Python Forum
Class code problem from CS Dojo YouTube - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Class code problem from CS Dojo YouTube (/thread-24215.html)



Class code problem from CS Dojo YouTube - Dixon - Feb-04-2020

class Robot:
def introduce_self(self)
print("My name is " + self.name)

r1 = Robot()
r1.name = "Tom"
r1.color = "red"
r1.weight = 30

r2 = Robot()
r2.name = "Jerry"
r2.color = "blue"
r2.weight = 40

r1.introduce_self()
r2.introduce_self()
With the above code, copied from the YouTube channel of CS Dojo, I get a traceback
"name 'r1' is not defined.


RE: Class code problem from CS Dojo YouTube - Larz60+ - Feb-04-2020

indentation is incorrect
Please supply URL


RE: Class code problem from CS Dojo YouTube - Dixon - Feb-04-2020

https://www.youtube.com/watch?v=wfcWRAxRVBA&t=45s

I typed in the code and didn't do the indents. I'm rather new to this forum, and didn't realize that using the python thingy wouldn't do the job. Anyway, when it's properly indented in Jupyter Notebook, it throws a Traceback.

Never mind. I didn't refresh a block of code after making changes, thus giving me the "name not found" error.


RE: Class code problem from CS Dojo YouTube - snippsat - Feb-04-2020

Can copy code under from YouTube link.
class Robot:
    def __init__(self, name, color, weight):
        self.name = name
        self.color = color
        self.weight = weight

    def introduce_self(self):
        print(f"My name is " + self.name)

# r1 = Robot()
# r1.name = "Tom"
# r1.color = "red"
# r1.weight = 30
#
# r2 = Robot()
# r2.name = "Jerry"
# r2.color = "blue"
# r2.weight = 40


r1 = Robot("Tom", "red", 30)
r2 = Robot("Jerry", "blue", 40)

r1.introduce_self()
r2.introduce_self()
Output:
My name is Tom My name is Jerry
So it's working.

Code over do i think is part-2,as you see some code is comment out.
To use comment out code it would be like this,also trow i in f-string.
class Robot:
    def introduce_self(self):
        print("My name is {self.name}")
Use:
>>> r1 = Robot()
>>> r1.name = "Tom"
>>> r1.color = "red"
>>> r1.name
'Tom'
>>> r1.introduce_self()
My name is Tom
So here is manually making the __init__ method in part 2.