Creating an Instance of a Class with a variable in Python

后端 未结 8 1267
野性不改
野性不改 2020-12-29 05:23

I\'m trying to create a game for my little sister. It is a Virtual Pet sort of thing and the Pet has toys to play with.

I created a class Toy and want t

相关标签:
8条回答
  • 2020-12-29 05:48

    If you haven't found it yet, here is Dive into Python's chapter on object-oriented programming.

    Here are some more examples, scroll to BankAccount.


    You can call a class directly to create an instance. Parameters are passed to the __init__ method.

    class Tamago(object):
        def __init__(self, name):
            self.name = name
    
    imouto = Tamago('imouto')
    oba = Tamago('oba')
    oba.name # 'oba'
    imouto.name # 'imouto'
    
    0 讨论(0)
  • 2020-12-29 05:49

    This is a very strange question to ask, specifically of python, so being more specific will definitely help me answer it. As is, I'll try to take a stab at it.

    I'm going to assume what you want to do is create a new instance of a datastructure and give it a variable. For this example I'll use the dictionary data structure and the variable mydictionary.

    mydictionary = dict()
    

    This will create a new instance of the dictionary data structure and place it in the variable named mydictionary. Alternatively the dictionary constructor can also take arguments:

    mydictionary = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
    

    Finally, python will attempt to figure out what data structure I mean from the data I give it. IE

    mydictionary = {'jack': 4098, 'sape': 4139}
    

    These examples were taken from Here

    0 讨论(0)
提交回复
热议问题